【问题标题】:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PointDto'元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“PointDto”
【发布时间】:2021-07-14 02:43:40
【问题描述】:

我正在检查 PointDto 对象(point1 和 point2)的 x1、y1 和 z1 字段的相等性

Eg :-
 point1 =>   PointDto: 
      {
        x1: "1.000000",
        y1: "1.0",
        z1: undefined
        pointIndex: 0,
      }
      
point2 =>   PointDto: 
      {
        x1: 1,
        y1: 1,
        z1: undefined
        pointIndex: 1,
      }   

const keys: any = {
  "x1": "x1",
  "y1": "y1",
  "z1": "z1"
}


const isEqual = (point1: PointDto, point2: PointDto) => {

  return keys.every((key :string) => (isNaN(point1[key]) ? point1[key] : +point1[key]) === point2[key]);

}

但是我收到了以下 typescript 错误,任何人都知道如何编写 (point1[key]) 以使 typescript 编译器满意

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型PointDtoNo index signature with a parameter of type 'string' was found on type PointDto.ts(7053)

【问题讨论】:

  • 请分享可重现的例子

标签: typescript ecmascript-6


【解决方案1】:

您的代码中有一些语法错误。但是为了防止出现以下错误:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PointDto'. No index signature with a parameter of type 'string' was found on type 'PointDto'.

您需要告诉ts 编译器keyPointDto 的键(keyof)。所以不是

(key :string) => isNaN(point1[key]) ? point1[key] : +point1[key]) === point2[key]);

使用这个:

(key :string) => {var k = key as keyof PointDto; (isNaN(point1[k]) ? point1[k] : +point1[k]) === point2[k]});

还有一件事:keys 不是数组,也没有every 函数。

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2021-04-20
    • 1970-01-01
    • 2020-11-13
    • 2019-12-17
    • 2020-10-29
    • 2020-10-04
    • 2019-12-15
    • 2021-09-22
    相关资源
    最近更新 更多