【问题标题】:TypeScript: Is there any way to have an Array of types using the typeof operator?TypeScript:有没有办法使用 typeof 运算符来拥有一个类型数组?
【发布时间】:2013-08-12 08:25:32
【问题描述】:

给定以下代码:

class Type
{
    static Property = 10;
}

class Type1 extends Type
{
    static Property = 20;
}

class Type2 extends Type
{
    static Property = 30;
}

我想创建一个函数,它可以返回一个类型数组,这些类型都继承自同一个基,允许访问类的“静态端”。例如:

function GetTypes(): typeof Type[]
{
    return [Type1, Type2];
}

所以现在理想情况下我可以走了:

GetTypes(0).Property; // Equal to 20

但是,似乎没有将多个 typeof 类型存储在数组中的语法。

这是正确的吗?

【问题讨论】:

    标签: arrays typescript typeof


    【解决方案1】:

    当然有。您的代码是正确的减去 GetTypes 函数的返回类型。 (要明确史蒂夫的回答也可以解决您的问题,这只是另一种不使用接口的方法。

    GetTypes函数的返回类型改为:

    function GetTypes(): Array<typeof Type>
    {
        return [Type1, Type2];
    }
    

    这应该是诀窍。

    【讨论】:

    • 是的,这就是我正在寻找的答案。我没想过使用 Array 构造函数来定义类型,我试图用 [] 表示法来做到这一点。
    【解决方案2】:

    这样做的正确方法是创建一个接口来描述类型(不属于该类型的实例)支持的属性(或操作):

    interface Test {
        x: number;
    }
    
    class MyType {
        static x = 10;
    }
    
    class MyOtherType {
        static x = 20;
    }
    
    var arr: Test[] = [MyType, MyOtherType];
    
    alert(arr[0].x.toString());
    alert(arr[1].x.toString());
    

    【讨论】:

      【解决方案3】:

      没有。目前仅支持单个标识符。我在这里提出了功能请求:https://typescript.codeplex.com/workitem/1481

      尽管如此,您可以简单地创建一个虚拟接口来捕获typeof Type,然后在数组中使用它,即:

      class Type
      {
          static Property = 10;
      }
      
      class Type1 extends Type
      {
          static Property = 20;
      }
      
      class Type2 extends Type
      {
          static Property = 30;
      }
      
      // Create a dummy interface to capture type
      interface IType extends Type{}
      
      // Use the dummy interface
      function GetTypes(): IType[]
      {
          return [Type1, Type2];
      }
      
      GetTypes[0].Property; // Equal to 20
      

      See it on the playground

      【讨论】:

      • 在语言规范中,它说类型查询表达式仅限于单个标识符或由句点分隔的标识符序列,这就是不允许使用数组语法的原因。请参阅第 3.6.3 节类型查询。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2011-05-30
      • 2019-12-20
      • 2021-01-08
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      相关资源
      最近更新 更多