Created
December 1, 2021 21:46
-
-
Save nrkn/31ea07765a4061337ed1708af9463ead to your computer and use it in GitHub Desktop.
Runtime typing
This file contains 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 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