代码之家  ›  专栏  ›  技术社区  ›  Patrick Hollweck

类中的类型脚本类型查询

  •  1
  • Patrick Hollweck  · 技术社区  · 8 年前

    通常类型查询的工作方式如下:

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

    { 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

    1 回复  |  直到 8 年前
        1
  •  2
  •   Patrick Hollweck    8 年前

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


    要键入query类成员的类型,可以使用多种方法:

    • 访问原型:

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

      App["states"]
      

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

    • 这种类型的多态性

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

      this["states"]
      

      不能 使用点运算符!必须改用对象索引运算符

    此类型查询在与类继承结合使用时非常有用

    例如,如果要对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

    我希望代码真的能在我度假的时候起作用,并且没有机会检查它。。。

    推荐文章