5

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!

1
  • 1
    The only way is to process the source code since interfaces don't exist at runtime. Something similar to what this library does. Commented Jun 21, 2017 at 3:05

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

This looks literally like my dream solution, thanks so much!
have you successfully used this package at all? I've been struggling to determine if this is user error or a problem with the package itself but I keep getting the following error: ts_transformer_keys_1.keys is not a function
No I have not used it in practice. Have you followed the guide on how to compile the program: github.com/kimamula/…? This is important step.
2

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.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.