Skip to content

Instantly share code, notes, and snippets.

@nrkn
Created December 1, 2021 21:46
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/31ea07765a4061337ed1708af9463ead to your computer and use it in GitHub Desktop.
Save nrkn/31ea07765a4061337ed1708af9463ead to your computer and use it in GitHub Desktop.
Runtime typing
import Ajv from 'ajv'
import { FromSchema } from 'json-schema-to-ts'
const productSchema = {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string' },
quantity: { type: 'number' },
type: {
type: 'string',
enum: [ 'FURNITURE', 'BOOK' ]
}
},
additionalProperties: false,
required: [ 'id', 'name', 'quantity', 'type' ]
} as const
type Product = FromSchema<typeof productSchema>
/*
type Product = {
id: number;
name: string;
quantity: number;
type: "FURNITURE" | "BOOK";
}
*/
const product: Product = {
id: 0,
name: '',
quantity: 0,
type: 'BOOK'
}
const bad: any = {
id: '',
name: 0,
type: 'FISH'
}
const ajv = new Ajv()
const isProduct = ( value: any ): value is Product =>
ajv.validate( productSchema, value )
const assertProduct = ( value: unknown ) => {
if( !isProduct( value ) ){
throw Error( ajv.errorsText( ajv.errors ) )
}
return value
}
console.log( isProduct( product ) )
console.log( isProduct( bad ) )
try {
const p = assertProduct( bad )
// if p passed assertion, it's a Product
const { id, name, type, quantity } = p
console.log( 'p is a Product', { id, name, type, quantity } )
} catch( err ){
console.error( err )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment