jsには、パラメータに従ってオブジェクトのリストに含まれるオブジェクトのプロパティを変更する関数があります。
function edit(object, key, property, value){
object[key][property] = value;
}
TypeScriptで同じ機能を実行するにはどうすればよいですか?
今から私はこれを作りました:
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[]; }'
次のような関数を呼び出せるようにしたい:
edit(myObject, "first", "oneProperty", "newValue1");
その結果、myObjectの「最初の」アイテムの「oneProperty」プロパティに「newValue1」が含まれることになります。
詳細:私のオブジェクトリスト
type SkillList = {
[key: string]: Skill;
};
私のオブジェクト
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 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
入力されたオブジェクト型を使用できるジェネリック型があります[key: string]: Skill;
。
次にK
、O
/内のすべてのキーを参照するジェネリック型がありますobject
。
その後、のP
すべてのプロパティを参照するジェネリック型がありますobject[key]
。
最後にO[K][P]
、typescriptにタイプを使用するように指示するものがありobject[key][property]
ます。これはおそらく最も便利な部分です。たとえば、string
sをnumber
sでオーバーライドするのを防ぐからです。edit(mySkillObject, "first", "name", "newValue1");
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加