【问题标题】:Creating computed class properties from array从数组创建计算类属性
【发布时间】:2020-09-04 19:56:49
【问题描述】:

我有一个字符串字面量数组,我想将其用作类的属性名称。

const propNames = ["a", "b", "c"] as const;

我想创建一个类

class Test {
    [name in typeof propNames[number]]: any;
}

但这会产生错误(在 WebStorm 检查中):

TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.
TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.
TS2693: 'number' only refers to a type, but is being used as a value here.

我可以用这些属性定义一个类型,例如

type Test = {
    [name in typeof propNames[number]]: any;
}

但我不知道如何将它变成具有这些属性的类。

我有一个我认为目前不可能的额外问题,但我可以通过将另一个字符串文字连接到它们来创建这些属性名称吗?

type Test = {
    [name + 'Prop' in typeof propNames[number]]: any;
}

【问题讨论】:

    标签: typescript literals computed-properties


    【解决方案1】:

    为什么不定义一个类型,然后通过:

    type Test = {
        [key: TEST]: any;
    } 
    

    其中 TEST 是类型。我从未尝试过这样做,但我知道它适用于原始类型。

    希望它能带你去你需要去的地方!

    【讨论】:

    • 我想在类而不是类型中定义属性(我已经可以做到)。另外,这似乎是语法错误? TS1023: An index signature parameter type must be either 'string' or 'number'.
    【解决方案2】:

    我通过定义中间类型并像命名空间一样使用它们来解决这个问题(包括额外的问题):

    const propNames = ["a", "b", "c"] as const;
    
    // using DOM types for demonstration
    type Canvases {
        [name in typeof propNames[number]]?: HTMLCanvasElement;
    }
    type Contexts {
        [name in typeof propNames[number]]?: CanvasRenderingContext2D;
    }
    
    // define class
    class Test {
        canvases: Canvases = {};
        ctxs: Contexts = {};
    }
    
    // now access on instances
    const t = new Test();
    t.canvases.a; // HTMLCanvasElement
    t.ctxs.b;     // CanvasRenderingContext2D
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多