Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

New type dynamically based on other type

I want to dynamically create a type based on another one or on readonly array.
Example:

const lines = ['one', 'two', 'three'] as const;
const linesWithA = lines.map(line => `${line}-A`);

Now I need a way to have a type for linesWithA. It can be for example a union type 'one-A' | 'two-A' | 'three-A', but it needs to be generated dynamically. So when I will manualy add an element to lines, then I don’t have to remember to change it for linesWithA type.

Is it possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you use the as const specifier within the map statement, then you can simply get all of the line types by indexing that array with number to get the items.

const lines = ['one', 'two', 'three'] as const;
const linesWithA = lines.map(line => `${line}-A` as const);
type LineWithA = typeof linesWithA[number]; // "one-A" | "two-A" | "three-A"

TypeScript Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading