【TS】エラー: 'string' 型の式は使用できないため、要素は暗黙的に 'any' 型を持ちます。

完全なエラー メッセージは次のとおりです。

「string」型の式はインデックス型に使用できないため、要素は暗黙的に「any」型になります。

このエラーは通常、値を取得するためにオブジェクトが使用されるシーンで発生します。

const obj = {
  name: '张三',
  age: 20,
};

const str = 'name' as string;

/**
  Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; age: number; }'.
  No index signature with a parameter of type 'string' was found on type '{ name: string; age: number; }'.ts
 */
obj[str];

エラー報告を避けるために、str が obj のキーであることを確認するだけで済みます。一般的に使用される方法は次のとおりです。

方法 1:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str = 'name' as string;

console.log(obj[str as keyof typeof obj]);

方法 2:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str = 'name' as string;

console.log(obj[str as keyof Person]);

これら 2 つのメソッドは非常に似ていることがわかります。ここで typeof が使用されていないのは、Person がオブジェクトではなく定義した型であるためです。2 つのメソッドで得られる結果は同じです。

// type T = 'name' | 'age'
type T = keyof Person;
type T = keyof typeof obj;

もちろん、str が型アサーションを使用しない場合は、次のようにこのように記述しても問題ありません。

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str = 'name';

console.log(obj[str]);

さて、別のシナリオを考えてみましょう。obj オブジェクトに多くの属性がある場合、obj オブジェクトのキーを多くの場所で使用することになります。すべてを keyof または keyof typeof にすることはできません。より良いものはありますか? 計画はどうですか? ?

方法 3:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str: keyof Person = 'name';

console.log(obj[str]);

obj に属性を追加したい場合はどうすればよいですか? 直接追加すると、次のようにエラーが報告されます。

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};
// Error: Property 'sex' does not exist on type 'Person'.ts
obj.sex = 'boy';

キーの値が obj オブジェクトに存在するかどうか不明な場合は、次のメソッドを使用できます。

interface Person {
  name: string,
  age: number,
  [key: string]: any,
}
const obj: Person = {
  name: '张三',
  age: 20,
};
obj.sex = 'boy';

おすすめ

転載: blog.csdn.net/weixin_38629529/article/details/127131932