[英]Using Typescript, Type guard and reflection to validate objects against types
I am trying to DRY, by using ES6, Typescript, I have created an interface, call it IUser which has properties. 我试图干,通过使用ES6,Typescript,我创建了一个接口,称之为具有属性的IUser。
I have seen examples using reflection and other techniques which test one property at a time. 我见过使用反射和其他技术的例子,它们一次测试一个属性。 But there must be a way to easily know if an object implements all properties, and if not which ones.
但是必须有一种方法可以很容易地知道一个对象是否实现了所有属性,如果不是哪个属性。
IKnowing that some properties are optional '?' 知道某些属性是可选的'?' and we know the type, this should be possible!
我们知道类型,这应该是可能的!
type IUser = {
name: string
age?: number
gender: string | any
}
// Assume this object gets created at runtime.
let john = {
name: "John"
}
let errors = ValidateThis(john, IUser)
// Return something like this ["Error: Missing value gender", "Warning: Missing optional value age"]
You aren't the first person to ask for this. 你不是第一个要求这个的人。 Interfaces don't exist at runtime, because TS fully erases all type information during compilation.
接口在运行时不存在,因为TS在编译期间完全擦除所有类型信息 。
However, ECMAScript has standards-tracked a reflection API, and TypeScript is on-board with it. 但是,ECMAScript标准跟踪了一个反射API,并且TypeScript随身携带。 Your best bet for accomplishing this is to use
experimentalDecoratorMetadata
to automatically decorate your classes with type information, and then use the reflection API at runtime to validate. 实现此目的的最佳选择是使用
experimentalDecoratorMetadata
自动使用类型信息装饰类,然后在运行时使用反射API进行验证。 (Ctrl-f and search for experimentalDecoratorMetadata
). (Ctrl-f并搜索
experimentalDecoratorMetadata
)。
This doesn't exist. 这不存在。 You should use one of the existing NPM projects, or write yet another.
您应该使用现有的NPM项目之一,或者编写另一个项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.