【问题标题】:How can I access index within object using a variable name in Typescript?如何使用 Typescript 中的变量名访问对象内的索引?
【发布时间】:2021-08-31 08:19:10
【问题描述】:

我定义了以下对象:

const routes = {
  "/": {},
  "/abc": {},
};

现在我想使用带有变量名的索引访问路由中的对象之一:

const indextoFind = "/abc";
const item = routes[indextoFind];

打字稿抛出:

元素隐含地具有“任何”类型,因为类型的表达式 'string' 不能用于索引类型 '{ "/": {}; "/abc": {}; }'。不 在“{”类型上找到带有“字符串”类型参数的索引签名 “/”:{}; "/abc": {}; }'。

索引显然是一个字符串,所以我不知道为什么它不允许我使用字符串变量访问对象。

另外,这工作得很好:

const item = routes["/abc"];

【问题讨论】:

标签: typescript


【解决方案1】:

出现此错误的最常见原因是您尝试将某种字符串指定为键,而 TypeScript 编译器无法解析此类型,因为它可以是任何字符串。要解决此问题,您可以使用 keyof typeofkeyof 之类的方式获取对象的键。

例子:

const routes = {
  "/": {},
  "/abc": {},
};

const indexToFind: keyof typeof routes = 'someInput'; // will not work
const item = routes[indexToFind];
const otherIndex: keyof typeof routes = '/';
const item2 = routes[otherIndex];

一个更好和更有用的例子是有某种函数,它需要一个对象的键:

const findSomething = (key: keyof typeof routes): Object => {
  return routes[key];
}

Reproduction link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-13
    • 2016-07-28
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多