Skip to content

Instantly share code, notes, and snippets.

@nrkn
Last active September 8, 2021 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrkn/1e5e6685c064dbea0b8ea68c2b75ff49 to your computer and use it in GitHub Desktop.
Save nrkn/1e5e6685c064dbea0b8ea68c2b75ff49 to your computer and use it in GitHub Desktop.
MyData
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