mardi 9 février 2021

Is it possible to create a random object from an arbitrary class using TypeScript?

I was intent on implementing a test helper that could work like this:

class MyClass {
    field1: string;
    field2: number;
}

const randomObject: MyClass = Magic.generateRandomObject(MyClass);

And then randomObject would have the fields field1 and field2 populated with values of the appropriate types.

However, I am not able to see how I could do that in TypeScript. Is it at all possible to have something like this in a language that in the end will be transpiled to JS? From what I have gathered, I could use reflect-metadata, but then I would have to only use classes that have fields annotated with some decorator that would populate the metadata, if I understood it correctly.





Aucun commentaire:

Enregistrer un commentaire