简体   繁体   English

使用Typescript,键入guard和reflection来根据类型验证对象

[英]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。

  • What is the best way to know if an object conforms to the interface at runtime? 在运行时知道对象是否符合接口的最佳方法是什么?
  • How can I get a list of the errors? 如何获取错误列表? The IDE knows which properties are missing, why I can't? IDE知道哪些属性丢失,为什么我不能?

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"]
  • I don't want to specify each property, so there must be a way to iterate the type properties. 我不想指定每个属性,因此必须有一种方法来迭代类型属性。
  • I don't want to use any of the existing npm projects I found which force me to create, yet a separate schema file or use a class. 我不想使用我发现的任何强制我创建的现有npm项目,而是使用单独的模式文件或使用类。

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.

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