简体   繁体   English

如何使用 TypeScript 实现对象验证?

[英]How to implement object validation using TypeScript?

I have an Express API server app and a React client app both implemented in TypeScript.我有一个 Express API 服务器应用程序和一个 React 客户端应用程序,它们都在 TypeScript 中实现。 I defined my data models using TypeScript interfaces, and I'm using those interfaces on both ends of the system.我使用 TypeScript 接口定义了我的数据模型,并且我在系统的两端都使用了这些接口。 However, TypeScript interfaces are compile-time feature only, and I need also runtime type checking, eg validating that HTTP POST data (json) conforms to the defined data structure.但是,TypeScript 接口只是编译时功能,我还需要运行时类型检查,例如验证 HTTP POST 数据 (json) 是否符合定义的数据结构。

So my question is, how could/should I implement runtime object validation utilizing the features provided by TypeScript?所以我的问题是,我可以/应该如何利用 TypeScript 提供的功能来实现运行时对象验证?

I've created a super lightweight library called Smoke Screen which does exactly that.我创建了一个名为Smoke Screen的超轻量级库,它正是这样做的。 It leverages typescript features to perform any kind of object validation within javascript runtime.它利用 typescript 功能在 javascript 运行时中执行任何类型的对象验证。 It's not 100% seamless due to the fact that javascript does not hold any type information at runtime, but thanks to TypeScript decorators, this may be easily done:由于 javascript 在运行时不保存任何类型信息,所以它不是 100% 无缝的,但是由于 TypeScript 装饰器,这可以很容易地完成:

class Person {

    @exposed({type: Number})
    age: number;

}

// serialize a Person object into a JSON string
const person = new Person();
person.age = 56.8;
const smokeScreen = new SmokeScreen();
smokeScreen.toJSON(person); // -> '{"age":56.8}'

// deserialize a JSON string into a Person object
let json = JSON.stringify({age: 19});
const person2 = smokeScreen.fromJSON(json, Person);
console.log(person2); // -> Person { age: 19 }

// typing validation
json = JSON.stringify({age: "oops"});
smokeScreen.fromJSON(json, Person); // Error: illegal input - property 'age' must be a number

Additional custom validators may be set, optional parameters and null checking are also supported and enforced.可以设置其他自定义验证器,还支持和强制执行可选参数和空检查。 I suggest reading more about it and trying it out.我建议阅读更多关于它的信息并尝试一下。

You can try out a framework/library called ts.validator.fluent .您可以尝试一个名为ts.validator.fluent的框架/库。 Generic object validation.通用对象验证。 Fluent rules.流利的规则。

https://github.com/VeritasSoftware/ts.validator https://github.com/VeritasSoftware/ts.validator

NPM Package : NPM 包

https://www.npmjs.com/package/ts.validator.fluent https://www.npmjs.com/package/ts.validator.fluent

Here is an example of how your TypeScript models can be validated using the framework:以下是如何使用框架验证 TypeScript 模型的示例:

/* Install npm package ts.validator.fluent and then import like below */
import { IValidator, Validator, ValidationResult } from 'ts.validator.fluent/dist';

/*TypeScript model*/
class Person {
   Name: string;
}

/* Validation rules */
var validatePersonRules = (validator: IValidator<Person>) : ValidationResult => {
  return validator
             .NotEmpty(m => m.Name, "Name cannot be empty")
        .ToResult();
};

/* Populate model */
var person = new Person();
person.Name = "Shane";

/* Validate model */
/* Sync */
var validationResult = new Validator(person).Validate(validatePersonRules); 
/* Async */
var validationResult = await new Validator(person).ValidateAsync(validatePersonRules);

I realize this question is old, but I just wrote my own validator for JSON objects and typescript, for this exact purpose, using decorators.我意识到这个问题很老,但我只是为 JSON 对象和打字稿编写了自己的验证器,为此目的,使用装饰器。 Available here: ts-json-object可在此处获得: ts-json-object

Example:示例:

import {JSONObject,required,optional,lt,gte} from 'ts-json-object'

class Person extends JSONObject {
    @required // required
    name: string
    @optional // optional!
    @lt(150) // less than 150
    @gte(0) // Greater or equal to 0
    age?: number
}

let person = new Person({
 name: 'Joe'
}) // Ok
let person = new Person({
}) // Will throw a TypeError, because name is required
let person = new Person({
 name: 123
}) // Will throw a TypeError, because name must be a string

Has many other features such as custom validations, etc.具有许多其他功能,例如自定义验证等。

I also didn't find any good solution for TypeScrpit which is:我也没有为 TypeScrpit 找到任何好的解决方案,它是:

  1. Simple to use使用简单
  2. Reusable with my existing code可与我现有的代码重用
  3. Share the same interfaces and logic as TypeScript与 TypeScript 共享相同的接口和逻辑

So I created a library called computed-types :所以我创建了一个名为计算类型的库:

const UserSchema = Schema({
  name: string,
  amount: number,
  flags: array.of(string).optional();
});

type User = Type<typeof UserSchema>;

Equivalent code in Joi : Joi 中的等效代码:

const UserSchema = Joi.object({
  name: Joi.string().required(),
  amount: Joi.number().required(),
  flags: Joi.array().items(Joi.string()),
});

type User = {
  name: string;
  amount: number;
  flags?: string[];
}

See more details and examples here: https://github.com/neuledge/computed-types在此处查看更多详细信息和示例: https : //github.com/neuledge/computed-types

This question is old, but I'd like to share my validation library also.这个问题很老,但我也想分享我的验证库。

It's type-script friendly , tiny (no tons of unnecessary functionality) and easily extensible by custom validators.它是type-script 友好的,很小(没有大量不必要的功能)并且可以通过自定义验证器轻松扩展。

npm: https://www.npmjs.com/package/checkeasy npm: https://www.npmjs.com/package/checkeasy

github: https://github.com/smbwain/checkeasy github: https : //github.com/smbwain/checkeasy

import {alternatives, arrayOf, int, object, oneOf, optional, string} from 'checkeasy';

const myValidator = object({
   a: int({max: 5}),
   b: string(),
   c: optional(float()),
   d: oneOf(['a', 'b', 7] as const),
   e: alternatives([string(), int()]),
   f: arrayOf(string()),
   g: object({
       subP: string(),
   }),
});

const value = myValidator(anyUnsafeData, 'name');
// type of value is: {
//    a: number,
//    b: string,
//    c: number | undefined,
//    d: "a" | "b" | 7,
//    e: string | number,
//    f: string[],
//    g: {subP: string},
//}

It also throws clear human readable messages in errors.它还会在错误中抛出清晰的人类可读消息。 Eg例如

myValidator({a: 'hello'}, 'data');
// throws: [data.a] should be an integer

myValidator({a: 1, b: 'string', d: 'a', e: true}, 'data');
// throws: All alternatives failed for [data.e]:
//      [data.e.@alternative(0)] should be a string
//      [data.e.@alternative(1)] should be an integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 express-validator 为嵌套对象实现验证 - How to implement validation using express-validator for the nested object 如何在Angular 2中使用Typescript类和接口实现“模式”以进行表单验证? - How to implement a “schema” with Typescript classes and interfaces in Angular 2 for form validation? 如何在 typescript 中实现选项 object 模式? - How do you implement the options object pattern in typescript? 如何使用 typescript 添加另一个 object 到 object? - How to add another object to an object using typescript? 如何使用 typescript 修剪 object 内部的 object - How to trim the object inside object using typescript 如何使用封装实现验证 - How to implement validation with encapsulation 如何使用 Typescript 实现 Material-UI ThemeProvider 和 WithStyles - How to implement Material-UI ThemeProvider and WithStyles using Typescript 如何在 xaml 中使用 typescript 实现动态菜单。 - How to implement dynamic menu using typescript in xaml. 如何使用Typescript在本机脚本中实现Observable - How to implement Observable in native-script using typescript 如何使用Office.js API在Excel中实现数据验证 - How to implement data validation in Excel using Office.js API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM