Home > Enterprise >  Automatically create object from interface in Typescript
Automatically create object from interface in Typescript

Time:12-04

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?

CodePudding user response:

Idk if this is exactly what you're looking for, but I know there is some tooling you can utilize:

https://ts-faker.vercel.app/ and https://github.com/google/intermock will be useful if your goal is json, not exactly what you're after, but I know I've been able to turn json into typescript using either IDE extensions, string replacement strategies using regex, or online tools such as:

https://www.convertsimple.com/convert-json-to-javascript/

CodePudding user response:

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