Hookyns / tst-reflect

Advanced TypeScript runtime reflection system
MIT License
341 stars 11 forks source link

Unable to get type arguments of class #49

Closed avin-kavish closed 2 years ago

avin-kavish commented 2 years ago

It looks like reading the type arguments of a class doesn't work. Inner Type of type aliases resolve correctly, but not classes.

type Foo<Type> = Type & {}

class Bar<Type> {}

@inject()
export class Baz {
  foo: Foo<string>   // type.innerTypes contains string

  bar: Bar<string>   // type.innerTypes is empty. type.getTypeParameters() returns Type. type.getTypeArguments() is empty
}
Hookyns commented 2 years ago

Fixed in tst-reflect-transformer@0.9.11

But type work differently than other generic types. type is resolved to it's definition. So type Foo<T> = T & {} is just union T & {}, cuz Foo does not rly exist.

Check this StackBlitz out.

avin-kavish commented 2 years ago

thanks for the fix!

While I'm here, isn't it possible to get types from the reference to a class ? i.e. getType(Foo) instead of getType<Foo>()

Hookyns commented 2 years ago

@avin-kavish It is now in tst-reflect@0.7.8.

It was possible to get type of value getType(new Foo()); just one line and you are able to get type of class itself getType(Foo).

avin-kavish commented 2 years ago

that's great!

I was considering the following about tst-reflect usage,

  1. Can't we use a decorator directly, without having to call a method that returns a decorator?
/**
 * @reflect
 */
function inject<TType extends Constructor>(ctor: TType) {
    const typeInfo = getType<TType>()
}

// usage
@inject
class Foo {}
  1. Can't we collect type info for all classes/interfaces in a project without using decorators? Maybe it's too slow?
Hookyns commented 2 years ago

@avin-kavish

  1. You can. https://github.com/Hookyns/tst-reflect/blob/main/tests/src/11-generic-class-decorator.ts @classDecorator
  2. Now all the types passed to getType<T>() and types decorated by decorators marked by @reflect are "reflected". \ Next version is prepared for generating metadata about all the modules and types. \ It's in progress and the latest progress is private until publish of final version.