TypeScript 错误 Index signature for type ‘X’ is missing in type ‘Y’ 修复

当 TypeScript 不认为使用索引签名的类型和更具体的类型兼容时,会出现错误“Index signature for type is missing in type”。 要解决该错误,需要在调用函数时使用扩展语法 (...) ,例如 accessEmployee({...employee}); 。

下面是产生该错误的一个示例

interface Employee {
  name: string;
  country: string;
}

const employee: Employee = {
  name: 'James',
  country: 'Germany',
};

const accessEmployee = (employee: { [key: string]: string }) => {
  return employee['country'];
};

// ⛔️ Error: Index signature for type 'string'
// is missing in type 'Employee'.ts(2345)
accessEmployee(employee);

TypeScript 错误 Index signature for type 'X' is missing in type 'Y' 修复

accessEmployee 函数将包含索引签名的对象作为参数。

示例中的索引签名意味着当一个对象被一个字符串索引时,它将返回一个字符串。

Employee 接口定义了一个具有字符串类型的名称和国家属性的对象。

不幸的是,TypeScript 认为更具体的 Employee 类型与索引签名不兼容。

解决这个问题的最简单方法是使用扩展语法 (...) 创建对象的浅表副本并让 TypeScript 识别它是兼容类型。

interface Employee {
  name: string;
  country: string;
}

const employee: Employee = {
  name: 'zadmei',
  country: 'China',
};

const accessEmployee = (employee: { [key: string]: string }) => {
  return employee['country'];
};

// ✅ Works now
accessEmployee({ ...employee }); // ?️ "China"

请注意,使用类型别名时不存在此限制。

// ?️ 现在使用类型别名
type Employee = {
  name: string;
  country: string;
};

const employee: Employee = {
  name: 'zadmei',
  country: 'China',
};

const accessEmployee = (employee: { [key: string]: string }) => {
  return employee['country'];
};

accessEmployee(employee); // ?️ "China"

这不是一个错误,而是设计使然,因为接口可以通过额外的声明来扩充,而类型别名则不能。

类型别名不能被扩充,因此推断类型别名的隐式索引签名比接口更“安全”。