Automatically create object from interface in Typescript

Viewed 267

I have this interface:

    interface MyInterface{
        first: string;
        second: string;
    }

I'd like to automagically create an object of that interface, with fake values, something like this:

    const myAutogeneratedObject: MyInterface = {
        first: "firstValue",
        second: "secondValue",
    };

So that if the interface changes to get a new field, my object will automatically have it.

How can this be done?

2 Answers

with an interface you can't. But you can with a class Providing default values is of course mandatory as well as the indexer [key: string]: any

class Test {
  [key: string]: any;
  prop1: string = "";
  prop2: string = "1";
  prop3: string = "lkj";
}
let arr: Array<Test> = [];

const a = new Test();
console.log({ a });

for (let i = 1; i <= 3; i++) {
  const c = new Test();

  const keys = Object.keys(c) as Array<Extract<keyof typeof c, string>>;

  keys.map((k) => (c[k] = "lklmkml"));

  arr = [...arr, c];
}

console.log(arr);
Related