You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Elegant and battle-tested validation library for type-safe input data for
TypeScript.
Introduction
Data entering your application from the outside world should not be trusted without
validation and often is of the any type, effectively disabling your type checker around
input values. It's an industry good practice to validate your expectations right at your
program's boundaries. This has two benefits: (1) your inputs are getting validated, and
(2) you can now statically know for sure the shape of the incoming data. Decoders help
solve both of these problems at once.
Basic example
import{array,iso8601,number,object,optional,string}from'decoders';// Incoming data at runtimeconstexternalData={id: 123,name: 'Alison Roberts',createdAt: '1994-01-11T12:26:37.024Z',tags: ['foo','bar'],};// Write the decoder (= what you expect the data to look like)constuserDecoder=object({id: number,name: string,createdAt: optional(iso8601),tags: array(string),});// Call .verify() on the incoming dataconstuser=userDecoder.verify(externalData);// ^^^^// TypeScript automatically infers this type as:// {// id: number;// name: string;// createdAt?: Date;// tags: string[];// }
Installation
npm install decoders
Requirements
You must set strict: true in your tsconfig.json in order for type inference to work
correctly!