TypeScript compiler API - Extract the type of union type tuple

410 Views Asked by At

If I have an array of type string[] and I want to extract the type from the array, I must do:

const typeArgs = type.typeArguments;
typeArgs[0]; // string

But what if I have a tuple of type [number, string] and want to get the type union of string | number?

1

There are 1 best solutions below

2
On

Getting the individual element types of a tuple type is the similar to getting the element of an array type—use the typeArguments property:

const [numberType, stringType] = type.typeArguments;

With the example below const arr: [string, number] = ['a', 1]; arr.map(el => el) I need to extract the el type.

If you have access to the el node then you can get it and ask what it's type is (TypeChecker#getTypeAtLocation). If you don't have access then, for what I know, it is not possible to create Type objects using the compiler API. Instead, I would suggest to create your own representation of that transformation based on the typeArguments property and use that in your code.