【问题标题】:Typescript type-queries in classes类中的打字稿类型查询
【发布时间】:2018-08-26 00:02:41
【问题描述】:

我正在尝试让 typescript 类型查询在类中工作。

通常类型查询是这样工作的:

const user = { name: "Patrick", age: 17 };
let typeofUser: typeof user;

在上面的示例中,“typeofUser”将具有以下类型:

{ name: string, age: number }

到目前为止一切顺利。但我试图让类型查询与类一起工作。 例如:

class App {
  states = {
    menu: {
      login() {
        console.log("Menu.login");
      }
    },
    game: {
      update() {
        console.log("Game.update");
      }
    }
  };

  constructor() {
    // FAILS => Cannot find name "states"
    const typeofStates: typeof states = {};

    // FAILS => Cannot find name "states"
    const keyofStates: keyof states = "game";
  }
}

我的问题是:如何访问类成员以进行类型查询, 使用“typeof”或“keyof”运算符?

Typescript playground sample

【问题讨论】:

  • typeof App.prototype.stateskeyof typeof App.prototype.states
  • App['states']keyof App['states']
  • 这两种解决方案都有效,你们中的一些人可以建议您的答案作为问题的答案,以便我接受吗?

标签: typescript


【解决方案1】:

感谢 cmets 中的@cartant。我自己回答这个问题,因为他没有发表他的评论作为答案。


要对类成员的类型进行类型查询,您可以使用多种方法:

  • 访问原型:

    App.prototype.states
    
  • 通过索引器访问它

    App["states"]
    

    需要注意的重要一点是,当成员为私有或静态时,此方法和上述方法可能不起作用。

  • 这个类型的多态

    在 Javascript 中有 this 的所有东西在 typescript 中都有一个“this type”。这个“this”类型可以像其他索引类型一样被查询。

    this["states"]
    

    注意:在尝试在另一个上下文中调用函数时,使用此技术可能会遇到问题。你也不能使用点运算符!您必须改用对象索引运算符

这种类型查询结合类继承非常有用

例如,如果您要对状态机进行编程,您可以拥有一个抽象的“状态机”类并使用 this-type-query 来获取子类中属性的类型

这可能看起来像这样:

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 寻找多态 this。

我希望代码真的可以工作我在度假,没有机会检查它......

【讨论】:

    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 2019-11-18
    • 2019-07-29
    • 2022-11-04
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多