添加新属性时映射类型出现 ts(1170) 错误

时间:2021-05-04 18:21:48

标签: typescript

我有以下代码:

enum A {
    FOO = 0,
    BAR = 1,
    BAZ = 2
}
type B = {
    [key in A]: number
}
declare let b: B;

它工作正常。我可以使用 b[A.FOO] 但不能使用 b[123]。但是,我也希望能够使用 b.length,但是当我添加属性以键入 B 时,就像这样...

type B = {
    length: number,
    [key in A]: number
}

...我收到以下错误

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您发现 {[K in XXX]: YYY} 形式的 mapped type 不允许附加属性。幸运的是,您可以通过使用 intersection type; 获得相同的效果。两个对象类型的交集具有两者的所有属性:

type B = {
    [key in A]: number
} & { length: number };

在您的特定情况下,由于所有这些属性都是 number 类型,您还可以使用单个映射类型,其中键类型是 A 枚举值的 unionliteral type "length"

type B = {
    [key in A | "length"]: number;
}

两个版本都可以如您所愿:

let b: B = {
    [A.FOO]: 12,
    [A.BAR]: 34,
    [A.BAZ]: 56,
    length: 78
} // okay

Playground link to code