TypeScript不允许我设置数组中对象的值



为什么TypeScript不允许我在一个数组中设置一个对象的值,我有它的确切位置?

list: AdminDefinitionType[];
activeIndex: number;
async updateDefinition(id: keyof AdminDefinitionType, value: string | number | boolean) {
if (value === this.list[this.activeIndex][id]) {
return true; // No Change
} else {
this.list[this.activeIndex][id] = value;  // 'string | number | boolean' is not assignable to type 'never' - WTF???
const definition: AdminDefinitionType = await clerk.update(this.list[this.activeIndex])
}
},

我觉得我什么都试过了。我认为这可能是因为它可能认为活动索引可能超出了范围,但我将其封装在if中,以确保它是并且仍然没有运气。

如何修复此错误?


更新

export type AdminDefinitionType = {
id?: number;
name: string;
sort: number;
disabled: boolean;
};

这是我的管理员定义类型。还有很多道具不需要在这里发布,但它们都是字符串类型的,不是可选的。

您需要指定键的类型。你可以用一个通用的来做到这一点

async updateDefinition<K extends keyof AdminDefinitionType>(id: K, value: AdminDefinitionType[K]) {
if (value === this.list[this.activeIndex][id]) {
return true; // No Change
} else {
this.list[this.activeIndex][id] = value; // OK
const definition: AdminDefinitionType = await clerk.update(this.list[this.activeIndex])
}
}

游乐场

最新更新