Jason Kuhrt
Jason Kuhrt

Reputation: 842

How can I use the TypeScript Compiler API to extract the type of an array

How can I use the TypeScript Compiler API to extract the type of an array? For example given this source:

let a: string[] = []

How can I go from getting the type string[] to just string?

ts-morph makes this easy but I haven't figured out how to replicate it with the raw TS Compiler API.

It seems that I need to use checker.getTypeArguments() but it wants a ts.TypeReference type which I don't know how to create.

Upvotes: 5

Views: 1027

Answers (1)

David Sherret
David Sherret

Reputation: 106590

An array type such as string[] will be in the form:

Array<string>

If you have one of these types, you can just assert it as a ts.TypeReference and pass it into TypeChecker#getTypeArguments:

const typeArgs = typeChecker.getTypeArguments(arrayType as ts.TypeReference);
const elementType = typeArgs[0];

To check if a type is an array type, I usually just check the type's symbol's name for Array and if it has a single type argument.

Upvotes: 4

Related Questions