TypeScript:元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引“Assignable”类型

时间:2021-06-18 09:29:55

标签: typescript

有以下脚本

class Assignable {
  constructor(properties: any) {
    Object.keys(properties).map((key: string) => {
      this[key as string] = properties[key]
    })
  }
}

抛出这个错误

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Assignable'.ts

知道为什么会发生这种情况以及如何解决它

1 个答案:

答案 0 :(得分:1)

你只需要在你的类上创建索引:

https://www.typescriptlang.org/play?#code/MYGwhgzhAECCUEsDmA7MAjEBTaBvAUNEdANoDWWAngFzQQAuATgikgLq1gqUDc+hxYAHsUDRgFdg9IYwAUAB0ZD5WRvQRYInbgEo8A4sQDy6AFZYpAOgqUICpSrUaIOywDMZAUTDAAFrJtoAF4APn1DCOJ6XwQIcio2YOhFZVV1TXjKNgMIgF8dPkNc-FygA

class Assignable {
    [key: string]: any;

    constructor(properties: any) {
        Object.keys(properties).forEach(key => {
            this[key] = properties[key]
        });
    }
}