项目作者: patrixr

项目描述 :
Miniature schema validator for Typescript (with type guards)
高级语言: TypeScript
项目地址: git://github.com/patrixr/wee-schema.git
创建时间: 2021-03-24T06:59:27Z
项目社区:https://github.com/patrixr/wee-schema

开源协议:MIT License

下载


Wee Schema

forthebadge
forthebadge

Miniature schema validator for Typescript (with type guards)

Usage

  1. import { weeschema, WeeSchema } from 'wee-schema'
  2. interface MyType {
  3. foo: string
  4. bar: number | string
  5. }
  6. // === Create the schema
  7. const schema : WeeSchema<MyType> = weeschema<MyType>({
  8. 'foo': ['string'],
  9. 'bar': ['number', 'string']
  10. })
  11. // === Use the schema
  12. function receive(thing: unknown) {
  13. thing.foo // ❌ generates a TS error
  14. // --- Using a type guard
  15. if (schema.ok(thing)) {
  16. console.log(thing.foo); // ✅ compiles + intellisense
  17. }
  18. schema.assert(thing);
  19. console.log(thing.foo); // ✅ compiles + intellisense
  20. }

Schema methods

  • ok Returns true if the object is of the correct type
  • assert Throws an error if the object is not of the right type
  • inspect Returns a list of error messages (if any)