Typescript泛型:子实例的返回类型

时间:2020-10-11 21:12:27

标签: typescript typescript-typings typescript-generics

我有一个看起来像这样的数据结构:

    interface A{
      propertyA: SubProperty<string>;
      propertyB: SubProperty<number>;
      propertyD: number;
    }
    type supported = string | number;
    class SubProperty<T extends supported>{
     data:T
    }
    
    
    type PropertyOfValue<T, V> = {
      [K in keyof T]-?: T[K] extends V
        ? K
        : never
    }[keyof T];
    
    type B = PropertyOfValue<A, SubProperty<supported>>;
    
    class ParentClass{
    constructor(protected a:A, protected b:B){}
    
    getSubPropertyType(){
    //  I would like that function to return the type of this.a[this.b].data
return typeof this.a[this.b].data;
    }
    }
    
    
    
    
    const a:A = {
      propertyA: new SubProperty<string>(),
      propertyB: new SubProperty<number>(),
      propertyD: 1
    }
    
    
    class ChildClass extends ParentClass{
    constructor(){
    super(a, 'propertyA');
    console.log(this.getSubPropertyType())
    }
    }
    
    var test = new ChildClass();
    console.log(test.getSubPropertyType())

如何告诉打字稿编译器test.getSubPropertyType()只能是字符串或未定义? 我该如何明确告诉他它不能是其他类型?

0 个答案:

没有答案