[英]Modify object property with a variable in typescript
在 js 中,我有一個 function,它根據參數修改 object 列表中包含的 object 的屬性:
function edit(object, key, property, value){
object[key][property] = value;
}
我將如何設法在 TypeScript 中執行相同的 function?
從現在開始,我做了這個:
function edit(object: ObjectList, key: string, property: string, value: number){
object[key][property] = value;
}
但這不起作用,並且給了我一個Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; mastery: number; parent_skill: number; access_level: number; cost: string; cost_value: number; background_color: number[]; font_color: number[]; description: string; required_skills: number[]; }'. No index signature with a parameter of type 'string' was found on type '{ name: string; mastery: number; parent_skill: number; access_level: number; cost: string; cost_value: number; background_color: number[]; font_color: number[]; description: string; required_skills: number[]; }'
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; mastery: number; parent_skill: number; access_level: number; cost: string; cost_value: number; background_color: number[]; font_color: number[]; description: string; required_skills: number[]; }'. No index signature with a parameter of type 'string' was found on type '{ name: string; mastery: number; parent_skill: number; access_level: number; cost: string; cost_value: number; background_color: number[]; font_color: number[]; description: string; required_skills: number[]; }'
我希望能夠像這樣調用 function:
edit(myObject, "first", "oneProperty", "newValue1");
結果將是我在 myObject 中的“第一個”項目的“oneProperty”屬性將具有“newValue1”。
更多信息:我的 object 列表
type SkillList = {
[key: string]: Skill;
};
我的 object
type Skill = {
name: string;
mastery: number;
parent_skill: number;
access_level: number;
cost: string;
cost_value: number;
background_color: number[];
font_color: number[];
description: string;
required_skills: number[];
};
答案是通用的 function:
function edit<O extends ObjectList, K extends keyof O, P extends keyof O[K]>(object: O, key: K, property: P, value: O[K][P]){
object[key][property] = value;
}
首先,我們有一個通用類型O
,它允許我們使用輸入的 object 類型,例如,可能縮小[key: string]: Skill;
.
然后我們有泛型類型K
,它引用O
/ object
中的所有鍵。
之后我們有泛型類型P
,它引用object[key]
中的所有屬性。
最后我們有O[K][P]
告訴 typescript 使用object[key][property]
的類型。 這可能是最有用的部分,因為它可以防止用number
s 覆蓋string
s,例如edit(mySkillObject, "first", "name", "newValue1");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.