Javascript TypeScript-元素隐式地具有一个';任何';类型,因为表达式的类型为';字符串';can';不能用于索引类型

Javascript TypeScript-元素隐式地具有一个';任何';类型,因为表达式的类型为';字符串';can';不能用于索引类型,javascript,typescript,Javascript,Typescript,假设我有这个: const color = { red: null, green: null, blue: null }; const newColor = ['red', 'green', 'blue'].filter(e => color[e]); 错误出现在底部附近的color[e]中,带有: 元素隐式具有“any”类型,因为表达式的类型为 “string”不能用于索引类型“{red:null;green:null;blue: null;}。未找到具有“s

假设我有这个:

const color = {
    red: null,
    green: null,
    blue: null
};

const newColor = ['red', 'green', 'blue'].filter(e => color[e]);
错误出现在底部附近的
color[e]
中,带有:

元素隐式具有“any”类型,因为表达式的类型为 “string”不能用于索引类型“{red:null;green:null;blue: null;}。未找到具有“string”类型参数的索引签名 在类型{red:null;green:null;blue:null;}上找到


我试着在TypeScript文档上到处寻找,但我该如何才能
接口
这样它才能接受
color[e]

你可以将
颜色
声明为
任意
,告诉TypeScript不要再做这件事(又称为显式任意):

但如果可能,最好使用强类型:

const color : { [key: string]: any } = {
    red: null,
    green: null,
    blue: null
};
有关TypeScript中索引的详细信息:



编辑:对于一个类似的问题,作者建议使用一个
映射
——如果它适合您的用例。

您遇到的问题不是
颜色
是错误的类型,而是TypeScript推断
['red'、'green'、'blue']
的类型是
字符串[]
。通常,这种类型的推理是可取的,因为(对于所有编译器来说)您可能希望将
'purple'
推到它上面。但在本例中,您希望编译器知道,唯一的成员是三个字符串文本
'red'
'green'
,和
'blue'
。也就是说,您需要一个至少与
数组
一样具体的类型

假设您使用的是TS3.4或更高版本,从编译器获得此类类型推断的最简单方法是使用:

as const
使编译器按照您设置的确切顺序推断出由数组中的三个字符串文本组成的字符串。(这甚至是一个错误)。这足以修复您的错误:

const newColor = (['red', 'green', 'blue'] as const).filter(e => color[e]); // okay
好吧,希望能有帮助。祝你好运


谢谢你的精彩回答。刚接触typescript并成功修复了我的第一个路障

  // in javascript world this is what I used to do.
  let values1 = products.reduce((acc, product) => {
      acc[product] = 1;
  //  ^  --> Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  // No index signature with a parameter of type 'string' was found on type '{}'.  TS7053

      return acc;
  }, {})

  // in typescript world I needed an extract type specification for 'acc'
  let values2 = products.reduce((acc: { [key: string]: number}, product) => {
      acc[product] = 1; //No more error
      return acc;
  }, {})

{[key:string]:any}
。。?TypeScript用
记录
类型覆盖了您。
const newColor = (['red', 'green', 'blue'] as const).filter(e => color[e]); // okay
  // in javascript world this is what I used to do.
  let values1 = products.reduce((acc, product) => {
      acc[product] = 1;
  //  ^  --> Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  // No index signature with a parameter of type 'string' was found on type '{}'.  TS7053

      return acc;
  }, {})

  // in typescript world I needed an extract type specification for 'acc'
  let values2 = products.reduce((acc: { [key: string]: number}, product) => {
      acc[product] = 1; //No more error
      return acc;
  }, {})