简体   繁体   中英

How to check type of type parameter in TypeScript

I need to check type of generic.

In type alias, I can do this:

type Obj<J, T> = J extends number ? {
    [x: number]: T
}: J extends string ? {
    [x: string]: T
}: never;

But in class, I can't:

class List<T = any> {
   private IsNumbered = T extends number;
}

Thank you for your time.

This is because you try to mix types and runtime values. TS has no reflection API, so it is not possible to use types to compute runtime values. To highlight this idea your example could be refactored as follows:

class Foo<T = any> {
   T value;
   get IsNumbered() {
       return typeof this.value === 'number';
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM