感谢评论中的@cartant。我自己回答这个问题,因为他没有把他的评论作为答案。
要键入query类成员的类型,可以使用多种方法:
此类型查询在与类继承结合使用时非常有用
例如,如果要对Statemachine进行编程,可以有一个抽象的“Statemachine”类,并使用this type查询来获取子类中属性的类型
可能是这样的:
abstract class Statemachine {
/* The typescript compiler won't actually infer "object" but
{
menu: {
login() => void
},
game: {
update() => void
}
}
> In case of the example below!
*/
abstract states: object
getState<K extends keyof this["states"]>(name: K): T[K] {
return this.states[name];
}
}
class Game extends Statemachine {
private states = {
menu: {
login() {
console.log("Menu.login")
}
},
game: {
update() {
console.log("Game.update") }
}
}
}
const game = new Game()
// Compiler error
game.getState("not a key of game.states")
// Works and intellisense for login()
game.getState("menu")
参考:
https://www.typescriptlang.org/docs/handbook/advanced-types.html
我希望代码真的能在我度假的时候起作用,并且没有机会检查它。。。