How can a typed array of strings be used as a union of literal types based on their actual values? On a high level, I have a typed array like ['hello', 'world']
and what I want to infer from that is a new type of 'hello' | 'world'
.
const someArray: Readonly<Array<string>> = ['hello', 'world'] as const;
type SomeType = typeof someArray[number]; // string
SomeType
will now be inferred to be string
instead of the union. How can I infer a union of the literal types?
This question is very similar to TypeScript array to string literal type with the difference, that the array is typed. I cannot remove that. The code below would work, but someArray
is actually typed as Array<string>
.
const someArray = ['hello', 'world'] as const;
type SomeType = typeof someArray[number]; // 'hello' | 'world'
Is there any way to narrow the inferred type accordingly?
edit: This example is obviously simplified. I use a third-party library that expects an array of objects. These are typed by the third-party and I cannot change that without loosing type support. I realize that it would work without a type, but I cannot realistically remove that.