ts-morph
ts-morph copied to clipboard
Question? How to extract type parameters from this case
In this case the type of Foo
becomes interned to Qux<1, 2> & 2
. This type is seen as an intersection. Its getText()
returns Bar<1,2>
. Its symbol name is Bar
. Its getTargetType
returns undefined
.
type Qux<A, B> = {}
type Bar<A, B> = Qux<A, B> & B
export type Foo = Bar<1, 2>
My question is this, then... How can we write logic to extract type parameters?
The logic I had before was:
- If
getTargetType
returns another type then try extracting type arguments from self viagetTypeArguments
- otherwise for aliases, classes, interfaces try extracting type parameters via
getTypeArguments
The idea that I could identify the generic type by checking t.getTargetType() === t
turns out to not always hold. For example here Qux<A,B>
object type returns undefined for t.getTargetType()
.
The problem then is that I am in a situation where I can't tell the difference between Foo<1, 2>
(should extract type arguments) and Qux<A, B>
(should extract type parameters).
... I am probably doing something wrong, but I can't tell what it is. I'm posting here on the off chance that ts-morph has a missing feature or bug.
https://stackoverflow.com/questions/65376601/how-to-extract-type-parameters-from-type-alias-type-arguments-from-generic-ins
When:
export type Foo = Bar<1, 2>
Gets interned to:
export type Foo = Qux<1, 2> & 2 // getText = Bar<1, 2> | type args = 1, 2
I could use the fact of type args 1, 2 to know that this intersection type is an instance of a generic with two type params. But I wouldn't know anything about the constraints, defaults, names, or ones with defaults that were not given type args.
So this doesn't work out as a solution.