简体   繁体   中英

Typescript: How can I construct an object of a particular type when I only have a type name?

I have some code that is needs to hydrate objects with types that are not known at compile time. (The code is in a library) From the type name, I would like to discover the type and construct it dynamically at runtime. The important operation here is running the default constructor and doing the other setup expected from the prototype. Is that even possible in typescript? How would I do it?

As @pan93412 said, Typescript's types are largely erased and not reified at runtime, and this is an explicit project goal. I would suggest trying to create a map of known type names to class constructors (or factory methods), and using those to reconstitute the objects:

https://www.typescriptlang.org/play?#code/MYGwhgzhAEDqCWATA5gUwC7QN4Chr+gHck10B9AM3lREWgF5oByMJnAXx1EhgBUALeADtk2PAXSCRlarQbMARm05cA9kIiZeATQAKAUQDK83ATgkMALnMoMAGnH4Bw5NeciO0SNmgBtdACeAA6o1poATi4AutZgQgHQKsDqmtAQqJFgIPAAXqh0jKYEqgoAVqjA6BDWvkwItuhMdszuyExRHDhqGqogqAB0IKrIABTpmdl5iP0l5ZUQ-QC2YEEjqgwAfNBCqITQOgaGvqpRIwCUF0A

Did you ask something about something like interface or type alias ? Well, it is not possible since TypeScript will clean out all the type information in the compiled JS - The type information would only be used on the type-checking of tsc , the metadata (need to be explicitly enabled) and the generated .d.ts which can't be used in runtime.

It is better to give us more explicit examples so we would be able to provide a better answer. :-)


I'm not sure about how the metadata in TypeScript works. I didn't write such a code before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM