Extend typescript to runtime — Part 2: using json schema

Image for post
Image for post
Photo by Pankaj Patel on Unsplash

Problem

Another solution

{
“title”: “Person”,
“type”: “object”,
“properties”: {
“firstName”: {
“type”: “string”
},
“lastName”: {
“type”: “string”
},
“age”: {
“description”: “Age in years”,
“type”: “integer”,
“minimum”: 0
},
“hairColor”: {
“enum”: [“black”, “brown”, “blue”],
“type”: “string”
}
},
“additionalProperties”: false,
“required”: [“firstName”, “lastName”]
}
import Ajv, { JSONSchemaType, DefinedError } from "ajv";
const validateObj = (obj: unknown) => {
const ajv = new Ajv();
const validate = ajv.compile({
title: "Example Schema",
type: "object",
properties: {
firstName: {
type: "string"
},
lastName: {
type: "string"
},
age: {
description: "Age in years",
type: "integer",
minimum: 0
},
hairColor: {
enum: ["black", "brown", "blue"],
type: "string"
}
},
additionalProperties: false,
required: ["firstName", "lastName"]
});
if (validate(obj)) {
// data is MyData here
console.log("It is a valid obj: ", JSON.stringify(obj));
} else {
console.log("It is not a valid obj: ", JSON.stringify(obj));
for (const err of validate.errors as DefinedError[]) {
console.log(err);
}
}
};
validateObj({});
validateObj({
firstName: "luke",
lastName: "skywalker",
age: 16,
hairColor: "black"
});
It is not a valid obj: {} {keyword: "required", dataPath: "", schemaPath: "#/required", params: Object, message: "should have required property 'firstName'"} It is a valid obj: {"firstName":"luke","lastName":"skywalker","age":16,"hairColor":"black"}
yarn add json-schema-to-typescript json2ts person.json > person.d.ts
export interface Person {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
hairColor?: "black" | "brown" | "blue";
}

Sum up

Image for post
Image for post

Written by

Full Stack Dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store