Home > Enterprise >  Create object based on types typescript
Create object based on types typescript

Time:11-24

Lest say I have this type

type foo = {
 go: string;
 start: string;
}

How can I dynamicaly made a function that will return

{ go: '', start: '' }

Is there any way on Type Script we could dynamically generate empty object based on solely just type? Or this is impossible because we cant just loop

I was thinking something like these

function generate<T>(T)<T>  {
 const obj = {}
 for (const key of keyof T) {
   obj[key] = ''
 }
 return obj
}

CodePudding user response:

You could make it generic, like this:

type foo<T extends string = string> = {
    go: T;
    start: T;
}

const test: foo<''> = {
    go: '',
    start: '',
};

TypeScript Playground

CodePudding user response:

This function should do what I think you want:

function generate<T>(type: (new () => T)): T {
    let obj = new type();
    Object.keys(obj).forEach(key => obj[key] = '');
    return obj;
}

It looks like you are passing type of the object as the argument, however what you are actually passing is a constructor for the object. This constructor is then called inside the function to create an object. The code then iterates over the fields in the object and sets them to ''. You could add a second argument to the function if you wanted to provide a string when calling generate.

Here is an example of its use:

class Foo {
    go: string;
    start: string;

    constructor(go: string, start: string) {
        this.go = go;
        this.start  = start;
    }
}

let o = generate(Foo);
console.log(o);

Output:

Foo: {
  "go": "",
  "start": ""
} 
  • Related