Leo Langinger
Leo Langinger

Reputation: 125

Generate object from Typescript interface

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

Answers (4)

Kas Elvirov
Kas Elvirov

Reputation: 7990

I did it by using intermock (Google) Here is a demo page

Upvotes: 1

Gustavo Lopes
Gustavo Lopes

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

Shaun Luttin
Shaun Luttin

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:

enter image description here

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

Amid
Amid

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

Related Questions