Andon Mitev
Andon Mitev

Reputation: 1514

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

Having following script

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

Throwing this error

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

any idea why this is happening and how to fix it

Upvotes: 0

Views: 188

Answers (1)

Andrei Tătar
Andrei Tătar

Reputation: 8295

You just need to create the index on your class:

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]
        });
    }
}

Upvotes: 1

Related Questions