How to Automatically Convert TypeScript Types to Runtime Validators

This article will show how to generate runtime validators from TypeScript files.

Tomas Nilsson
JavaScript in Plain English

--

Photo by Tudor Baciu on Unsplash

As a developer, it’s probably a good thing to be lazy. If some code has been written once (like TypeScript definitions), why write similar code that does the same thing again? It’s error-prone and takes a lot of time. What if there was a way to convert those Types, Enums and Interfaces into some kind of runtime code? Well, there is.

This article demonstrates the package runtime-typescript-checker , which can be found at https://www.npmjs.com/package/runtime-typescript-checker.

TL;DR

This article explains how to automatically generate functions IsUserTypeGuard() and ValidateUser() from:

export interface User {
Name: string;
HasPaid: "Yes" | "No",
Notes?: string
}

Build

First the runtime-typescript-checker will parse the source code (TypeScript files containing exported Types, Enums and Interfaces).

At the end of the parse, new files will be created (or updated) which can be used.

Example

Will generate a file with two functions for each exported type. One TypeGuard and one Validator-function.

Using the tests in runtime (TypeGuard)

A few lines of code are required to initialize the runtime checker, but after that has been completed, it’s only to use:

Using the tests in runtime (Validate)

TypeGuards are great, but often there’s a need for the details about the errors. As said before, there is also a validator function which clearly presents the errors found in the payload:

So given the above interfaces, this payload:

{
Name: "Tomas",
HasPaid: "Maybe",
Role: dances.eRole.Leader,
DanceClass: {
ID: "7",
Name: "Lindy Hop Autumn",
Level: "?",
},
Notes: undefined,
MemberShip: true
}

Would render the following errors:

[
{
"instancePath": "/HasPaid",
"schemaPath": "#/properties/HasPaid/enum",
"keyword": "enum",
"params": {
"allowedValues": [
"No",
"Yes"
]
},
"message": "must be equal to one of the allowed values"
},
{
"instancePath": "/DanceClass/Level",
"schemaPath": "#/properties/DanceClass/properties/Level/enum",
"keyword": "enum",
"params": {
"allowedValues": [
"A",
"B",
"C",
"D",
"E"
]
},
"message": "must be equal to one of the allowed values"
}
]

Demo?

git clone https://github.com/tomnil/runtime-typescript-checker-demo
cd runtime-typescript-checker-demo
npm install
# And then one of the following:npm run build-example1
npm run build-example1-force
npm run test-example1

There’s more information on the Demo project page.

Enjoy

:)

More content at plainenglish.io

--

--