Reputation: 13663
Note: This question is about the TypeScript compiler API, not about TypeScript as a language!
I have a value of type ts.Type
. I want to know what type it represents: Is it a number? A function? An array?
I found that type.flags
allows me to perform roughly the static equivalent of the typeof
operator, allowing me to differentiate between primitive types such as number
, string
, and boolean
(but not functions). Anything else -- arrays, functions, POJOs, etc. -- simply has the TypeFlags.Object
flag.
How can I further examine these non-primitive types? How do I determine whether a type is an array, a function, an enum, a class instance...?
Upvotes: 3
Views: 348
Reputation: 9380
First off I'd say go play around with https://typescript-eslint.io/play/. Drop in some code, select the TypeScript tab, and click around. As you select notes in the tree it'll show you decoded values of the kind
and flags
properties.
It's much nicer than the helper I'd started off with to decode the flags:
function activeFlags(flagEnum: any, flagValue: number) {
return Object.entries(flagEnum)
.filter(([, value]) => typeof value === 'number' && (flagValue & value) !== 0)
.map(([key]) => key);
}
activeFlags(ts.NodeFlags, tsNode.flags);
Upvotes: 0
Reputation: 556
There is another field on types that have Typeflags.Object
.
Its called type.objectFlags
and you can use it to further distinguish the type
Upvotes: 0