错误 TS7053:元素隐式具有 'any' 类型,因为 'string' 类型的表达式不能用于索引 'ModuleType'

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index 'ModuleType'

我有类型

type Link = {
  type: number | string;
  productIds: Array<string>;
};

export type ModuleType = {
  '@type': string;
  title: string;
  text: string;
  position: string;
  backgroundStyle: string;
  latitude: string;
  longitude: string;
  background: File;
  link: Link;
};
const formDataType = formData[link].type;

这里 formData 有一个 ModuleType 类型,我正在尝试使用字符串获取对象键,但我在 TS 中遇到错误:TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ModuleType'.   No index signature with a parameter of type 'string' was found on type 'ModuleType'. 我需要从对象

中获取 link 键

提前致谢!

你必须告诉 TypeScript 关键字名称是 ModuleType 类型的键。

为此你必须这样写,


let name : keyof ModuleType = 'Whatever value it contains';

const formDataType = formData[name].type;

//  or

const formDataType = formData[<keyof ModuleType>name].type;