【问题标题】:TypeScript using type parameterTypeScript 使用类型参数
【发布时间】:2014-02-19 11:36:02
【问题描述】:

如何在下一个代码块(typeOf、instanceOf、...)中使用类型参数 T。 T 是“组”。是否有可能是因为 JavaScript 没有类型。谢谢。

export class LocalStorage<T> implements ILocalStorage<T> {
    constructor() {}

    getKey(): string {
        if (T is 'Group')
            return "Groups";
    }
}

【问题讨论】:

    标签: javascript typescript instanceof typeof type-parameter


    【解决方案1】:

    您不能为泛型中的 TypeArguments 这样做(正如您已经意识到的那样)。但是如果你使用 TypeScript 类,你可以进行运行时检查:

    class Group{}
    
    
    function getKey(item:any): string { 
        if (item instanceof Group)
            return "Groups";
        else
            return 'invalid';
    }
    
    
    console.log(getKey(new Group()));
    

    上面的代码中没有 typescript 魔法。我们只是使用 javascript instanceof 运算符:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

    【讨论】:

      【解决方案2】:

      感谢巴萨拉特。你指出我正确的方向。我的代码现在看起来更好了。

      export class LocalStorage<T> implements ILocalStorage<T> {
          private instance: any;
          constructor(instance: any) {
              this.instance = new instance(null);
          }
      
          getKey(): string {
              if (this.instance instanceof g.Group)
                  return "Groups";
              else 
                  return "Invalid";
          }
      }
      
      //using
      var groupLocalStorage = new ls.LocalStorage<g.Group>(g.Group);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-05
        • 2021-01-21
        • 2017-05-19
        • 2021-07-10
        相关资源
        最近更新 更多