元素隐式具有“any”类型,因为 expression 不能用于索引联合类型

Element implicitly has an 'any' type because expression can't be used to index union type

提问人:gxc 提问时间:8/17/2023 更新时间:8/17/2023 访问量:84

问:

鉴于以下打字稿代码,为什么我不能使用“name”来索引“result”,我该如何让它工作?

export type Registry = typeof registry;
export type Name = keyof Registry;

export function parser(name: Name) {
  const result = registry[name]()
  if (name in result) {
    return result[name];
  }
}

export const registry = {
  Dog: () => ({ Dog: '../Dog' }),
  Cat: () => ({ Cat: '../Cat' }),
};

这是我收到的 TS 错误:

Element implicitly has an 'any' type because expression of type '"Dog" | "Cat"' can't be used to index type '{ Dog: string; } | { Cat: string; }'.

TypeScript 映射 Typeguards 类型缩小

评论


答:

0赞 AztecCodes 8/17/2023 #1

TypeScript 索引问题

TypeScript难以理解参数与尝试为其建立索引的对象类型之间的类型关系。但是,由于是 的键,因此无法推断对象与用于索引的参数具有相同的键。nameresultnamenameRegistryTypeScriptresultnameregistry

修复:告知对象将具有与参数相同类型的键。您可以使用 来执行此操作。TSresultnamegenerics

我的代码:

// Variables
export type Registry = typeof registry;
export type Name = keyof Registry;

// Parser Function
export function parser<T extends Name>(name: T): string {
  const result = registry[name]();
  if (name in result) {
    return result[name];
  }
  return '';
}

export const registry = {
  Dog: () => ({ Dog: '../Dog' }),
  Cat: () => ({ Cat: '../Cat' }),
};