4

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.

Jason Kuhrt
  • 736
  • 1
  • 4
  • 12
  • 1
    Does this answer your question? [Test for array of string type in TypeScript](https://stackoverflow.com/questions/23130292/test-for-array-of-string-type-in-typescript) – Jay Mar 10 '20 at 01:52
  • 1
    I'm asking at the meta level, TypeScript Compiler API. Title updated accordingly. – Jason Kuhrt Mar 10 '20 at 02:05
  • See also https://stackoverflow.com/questions/45660003/find-kind-of-typereference-using-typescript-api – Jay Mar 10 '20 at 02:14

1 Answers1

3

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.

David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • 5
    Thanks David, what eluded me was the type cast. Is there no other way? And how did you figure this out? Is it expected that API users should intuit usage like this or did you learn this by e.g. talking to the core team over gitter etc.? – Jason Kuhrt Mar 15 '20 at 17:14