自我实例的类型

时间:2018-10-22 23:56:57

标签: typescript

class ThingOne {
  one: '1'
  public constructor(choice: keyof me) {
    console.log(this[choice])
  }
}
class ThingTwo extends Thing {
  two: '2'
}
new ThingOne('one') // 1
new ThingOne('two') // TypeError
new ThingTwo('two') // 2

在此示例中,有什么可以代替“我”的东西吗? (减去使用泛型来明确地做到这一点)

1 个答案:

答案 0 :(得分:2)

对于非静态实例成员,可以使用this多态类型:

class ThingOne {
    one: '1'
    public do(choice: keyof this) {
        console.log(this[choice as keyof this])
    }
}
class ThingTwo extends ThingOne {
    two: '2'
}
new ThingOne().do('one') // 1
new ThingOne().do('two') // TypeError
new ThingTwo().do('two') // 2

不幸的是,this在构造函数参数中不可用。您可以通过几种方法来解决此问题,一种方法是向类添加一个通用参数,该参数将成为获取键的类型,并使用一些条件类型的魔术使其正常工作:

class ThingOne<T extends ThingOne = never> {
    one: '1'
    public constructor(choice: T extends never ? keyof ThingOne: keyof T)
    public constructor(choice: keyof ThingOne) {
        console.log(this[choice as keyof this])
    }
}
class ThingTwo<T extends ThingTwo = never> extends ThingOne< T extends never ? ThingTwo: T> {
    two: '2'
}
new ThingOne('one') // 1
new ThingOne('two') // TypeError
new ThingTwo('two') // 2

有一个关于该主题的GitHub issue,它可能会在以后实现,请在执行上述解决方法之前检查票证。

相关问题