[英]Get available properties of interface without initializing
I'm trying to create a generic "mapping" method that can take an interface and JSON response then map the available keys to the interface.我正在尝试创建一个通用的“映射”方法,该方法可以采用接口和 JSON 响应,然后将可用键映射到接口。 The issue I'm having is there seems no way to get the available properties of an interface without initializing them.我遇到的问题是似乎无法在不初始化的情况下获取接口的可用属性。
Is there a way to get the value of an interface without having to define it?有没有办法获得接口的值而不必定义它?
Interfaces and other type information (with exceptions) are not available at runtime.接口和其他类型信息(有例外)在运行时不可用。
However, you can define a method that deserializes a JSON string into a given type.但是,您可以定义将 JSON 字符串反序列化为给定类型的方法。 const myThing: IThing = JSON.parse(myJsonString);
will cast it to the type IThing
.将其转换为IThing
类型。
If you have a class Thing
that implements IThing, you can use Object.keys
to iterate over the keys of an instantiated Thing
, and match the key indices together, like thing[key] = JSON.parse(...)[key]
如果您有一个实现 IThing 的类Thing
,您可以使用Object.keys
迭代实例化Thing
的键,并将键索引匹配在一起,例如thing[key] = JSON.parse(...)[key]
interface
and types
in typescript are only checked when compiling (from ts to js). typescript 中的interface
和types
只在编译时检查(从 ts 到 js)。 So, at runtime (which runs js), there is no information about interface.因此,在运行时(运行 js),没有关于接口的信息。
But you can implement this with use of class
and reflect-metadata
and decorators
, like class-transformer
do.但是您可以像class-transformer
一样使用class
和reflect-metadata
以及decorators
来实现这一点。
Simply switching my interfaces to a class was the solution.简单地将我的接口切换到一个类就是解决方案。 I am then able to create a blank instance and list out all available properties.然后我就可以创建一个空白实例并列出所有可用的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.