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?
CodePudding user response:
Yes, it's possible:
type lines = 'one' | 'two' | 'three'
type linesWithA = `${lines}-A`
This feature of TypeScript is called Template Literal Types, and it was introduced in version 4.1.
You can try the example above on the TS Playground here
CodePudding user response:
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"