patterntypescriptCritical
TypeScript array to string literal type
Viewed 0 times
typescriptarrayliteralstringtype
Problem
I currently have both an array of strings and a string literal union type containing the same strings:
I need both in my application, but I am trying to keep my code DRY. So is there any way to infer one from the other?
I basically want to say something like
const furniture = ['chair', 'table', 'lamp'];
type Furniture = 'chair' | 'table' | 'lamp';I need both in my application, but I am trying to keep my code DRY. So is there any way to infer one from the other?
I basically want to say something like
type Furniture = [any string in furniture array], so there are no duplicate strings.Solution
TypeScript 3.4+
TypeScript version 3.4 has introduced so-called const contexts, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown below in the 3.0 solution).
With this new syntax, we get this nice concise solution:
More about the new const contexts is found in this PR as well as in the release notes.
TypeScript 3.0+
With the use of generic rest parameters, there is a way to correctly infer
It goes like this:
More about generic rest parameters
TypeScript version 3.4 has introduced so-called const contexts, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown below in the 3.0 solution).
With this new syntax, we get this nice concise solution:
const furniture = ['chair', 'table', 'lamp'] as const;
type Furniture = typeof furniture[number];More about the new const contexts is found in this PR as well as in the release notes.
TypeScript 3.0+
With the use of generic rest parameters, there is a way to correctly infer
string[] as a literal tuple type and then get the union type of the literals.It goes like this:
const tuple = (...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];More about generic rest parameters
Code Snippets
const furniture = ['chair', 'table', 'lamp'] as const;
type Furniture = typeof furniture[number];const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];Context
Stack Overflow Q#44497388, score: 383
Revisions (0)
No revisions yet.