Typescript interface implementation does not affect index signature

For my new small project, I decided to go with typescript for some reason no better than making myself feel like c programming on wonderful steroids and apparently I am paying a price.

I have an interface on the right

export default interface DataObject {
  [key: string]: any
};

This supposedly allows me to define objects with string keys and any values. Then i implement it

import DataObject from "./data-object";

export default class Model implements DataObject {

  constructor(data: DataObject = {}) {
    Model.fill(this, data);
  }

  static fill(model: Model, data: DataObject) {
    for (let prop in data) {
      model[prop] = data[prop];
    }
  }
}

Now i get this error

An element is implicitly of type "any" because the type of "Model" has no index signature

in this line

      model[prop] = data[prop];

But if I modify my model to include a signature

import DataObject from "./data-object";

export default class Model implements DataObject {

  [key: string]: any;

  ...
}

Then there is no mistake.

Why does the interface signature not affect my class?

+4
source share
1

, . , , . , -, , ( Playground).

interface DataObject {
    foo: any;
    bar: any;
    [key: string]: any;
};

class Model implements DataObject {

    private _bar: string = null;
    public get bar(): string {
        return this._bar;
    }
    public set bar(value: string) {
        this._bar = value;
    }

    constructor(data: DataObject = {}) {
        this.foo = "bar"; // error
        this.bar = "foo"; // no error
        Model.fill(this, data);
    }

    static fill(model: Model, data: DataObject) {
        for (let prop in data) {
            model[prop] = data[prop]; // error
        }
    }
}

class DataObject2 {
    foo: any;
    bar: any;
    [key: string]: any;
};

class Model2 extends DataObject2 {

    constructor(data: DataObject2 = { foo: "", bar: "" }) {
        super();
        this.foo = "bar"; // no error
        this.bar = "foo"; // no error
        Model2.fill(this, data);
    }

    static fill(model: Model2, data: DataObject2) {
        for (let prop in data) {
            model[prop] = data[prop]; // no error
        }
    }
}
+1

Source: https://habr.com/ru/post/1685655/


All Articles