在TypeScript中使用预定义类型索引签名

ocebsuys  于 2022-12-05  发布在  TypeScript
关注(0)|答案(1)|浏览(161)

下面的代码:
我的目标是attribute1将是number[],attribute2将是string[],attribute3将是number[]。如果我试图执行下面的obj.attributes.attribute2 = [1, 2, 3];行,我如何使用typescript实现这一目标,以便出现编译错误

type MyFields = "attribute1" | "attribute2" | "attribute3";
type MyTypes = number[] | string[] | number[];

interface DynamicType {
  attributes: {
    [attribute in MyFields]: MyTypes;
  };
}

const obj: DynamicType = {
  attributes: {
    attribute1: [],
    attribute2: [],
    attribute3: [],
  },
};

obj.attributes.attribute1 = [1, 2, 3];
obj.attributes.attribute2 = [1, 2, 3]; // i need to have a compilation error here!
obj.attributes.attribute1 = [1, 2, 3];
osh3o9ms

osh3o9ms1#

使用类型Assert来指定属性对象中每个属性的类型。

const obj: DynamicType = {
  attributes: {
    attribute1: [] as number[],
    attribute2: [] as string[],
    attribute3: [] as number[],
  },
};

obj.attributes.attribute1 = [1, 2, 3];
obj.attributes.attribute2 = ["a", "b", "c"];
obj.attributes.attribute3 = [4, 5, 6];

TypeScript编译器会给予您一个错误,因为attribute2属性被定义为string[],而您正试图给它分配一个type number[]的值。

相关问题