Creating a Typescript union, while also having runtime access to the values 0 ▲ Jamie Tanna 1 hour ago · Tech · hide · 0 comments I very regularly end up writing this pattern - primarily in Renovate's code - so thought I'd write it up as a form of blogumentation, so I can refer back to it in the future. (This example uses concepts from the Renovate codebase, but does not take any code from it) For instance, let's say that you have a known union of big Git-hosting platforms - github, gitlab and forgejo. If you wanted to make sure that a given function parameter could only include them, you'd write i.e. export type Platform = 'github' | 'gitlab' | 'forgejo`; Normally this would be sufficient for usage, and nothing else is needed. But if you then want to be able to reference the ?? - for instance, as part of generating documentation - then you need some way of accessing each of these values at runtime. This leads us to: export const Platforms = [ 'github', 'gitlab', 'forgejo', // no shade to other platforms ] as const; // `as const` is important! export type Platform = (typeof Platforms)[number]; Now, you can… No comments yet. Log in to reply on the Fediverse. Comments will appear here.