[SOLVED] New type dynamically based on other type

Issue

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?

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

Answered By – sno2

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *