Reputation: 125
I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this:
interface Foo {
bar: string
}
const generateObjFromInterface = (Foo) => // { bar: 'string'}
I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information!
Thanks in advance!
Upvotes: 5
Views: 4079
Reputation: 24
I also was searching for something that could do it and I didn't find anything. So I build this lib https://www.npmjs.com/package/class-validator-mocker, which can generate random data for classes attributes annotated with class-validator's decorators. Worked pretty well for my purposes.
Upvotes: 0
Reputation: 141622
Since TypeScript's interfaces are not present in the JavaScript output, runtime reflection over an interface is impossible.
Given this TypeScript:
interface Foo {
bar: string
}
This is the resultant JavaScript:
Since there is no JavaScript, what you want to do is categorically impossible is very contrived.
Edit: Come to think of it, you could find, read, and parse the *.ts source file at runtime.
Upvotes: 2
Reputation: 22372
It is possible. As typescript 2.4 is around the corner we can use custom transformers for typescript during compilation and get the list of all properties that are there and as a result create object with such properties.
Here is an example, but please note - as I have said this require to use typescript 2.4+ that is not yet in stable release
Upvotes: 3