Last active
September 8, 2021 00:20
-
-
Save nrkn/1e5e6685c064dbea0b8ea68c2b75ff49 to your computer and use it in GitHub Desktop.
MyData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {FromSchema} from 'json-schema-to-ts' | |
import Ajv from 'ajv' | |
const ajv = new Ajv() | |
const schema = { | |
type: 'object', | |
properties: { | |
foo: { type: 'integer' }, | |
bar: { type: 'string' } | |
}, | |
required: [ 'foo' ], | |
additionalProperties: false | |
} as const | |
// we can derive the literal type directly with typeof because we used "as const" at the end | |
type MyDataSchema = typeof schema | |
// this type is exactly what you would expect | |
type MyData = FromSchema<MyDataSchema> | |
const validate = ajv.compile<MyData>( schema ) | |
// type as any to mock getting from unknown source | |
const data: any = { | |
foo: 1, | |
bar: 'abc' | |
} | |
if( validate( data ) ){ | |
console.log( data.foo ) | |
} else { | |
console.log( validate.errors ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment