TS Dynamic Type Checker
TypeScript library that performs dynamic type checking
TypeScript is great. It warns you of static type errors and hence earns you lots of time and headaches. But your program probably have entrypoints (network requests, file readings, etc.) that can not be trusted completely.
For instance, supose you read some configuration from a JSON
file:
; ; readFile'./my-aws-config.json', ,;
In this example, TypeScript can not prevent errors if the read JSON doesn't have an expected property. These are some cases this library was created for.
Features
- Infers typings.
- Very lightweight (under 4kb without minifying).
- Expressive errors.
- Works both client and server-side.
Installation
npm install --save ts-dynamic-type-checker
Usage
The main concept behind the library is "contracts". A contract is an identity function that throws a TypeError
if the parameter doesn't have the expected type.
For example if you pass a string
to the str
contract, it will return the same value, for other types it will throw a TypeError
:
; str'Hello world'; // <- Returns 'Hello world'str8 as any; // <- Throws a TypeError
Check for specific values
;; ;; ; ; // <- static error. It will be warned by TypeScript itself. readLine.question'Which is your favourite fruit?',;
It's important to notice that while str
is a contract itself, oneOf
is not. oneOf
is a function that returns a contract. You can think of it like a contract builder.
There are some other functions that help you build contracts
. For instance, there is arrOf
:
; ; onlyNumbers; // <- Returns [1, 2, 3]onlyNumbers as any; // <- Throws a TypeError ; onlyHobbits; // <- Returns the arrayonlyHobbits; // <- Throws a TypeError
As you can see, arrOf
takes a contract as parameter and returns another contract.
Last, but not least, the objOf
function is perhaps the most usefull one:
; ; ; // xhr function from any library you likexhr'/URI/to/people' .thenpeopleValidator .then/* The `people` variable is guaranteed to have the shape you have defined... */;
Notice that the objOf
function takes an object that describes the shape of the expected objects as a parameter. That object's properties are contracts.
Type inference
It's important to mention that all the contracts are typed and TypeScript with prevent errors if the parameters are incorrect and will inferere the output:
; str9; // TypeScript will error ("string expected").; // TypeScript will infere it's a number. ; fooBarContract; // <- Typescript will error ; // <- TypeScript will infer type {foo: string; bar: number;}
API
contracts
Built-in Function | Type | Example |
---|---|---|
bool |
IContract<boolean> |
bool(true); |
num |
IContract<number> |
num(89); |
str |
IContract<string> |
str('Hello world'); |
undef |
IContract<undefined> |
undef(undefined); |
nil |
IContract<null> |
nil(null); |
arr |
<T> IContract<T[]> |
arr([1, 2, 3]); |
obj |
<T extends object> IContract<T> |
bool({foo: 'foo'}); |
regExp |
IContract<RegExp> |
regExp(/^hello/i); |
date |
IContract<Date> |
date(new Date()); |
anything |
<T> IContract<T> |
anything(4); |
never |
IContract<never> |
never(4 as never); |
anything
A note on anything
is just an identity function that will never throw a TypeError
. Its static type will be inferred from the value if possible or will default to any
. It's useful with another functions like objOf
(view below). For instance you can define a contract like:
;
never
A note on You may think the never
contract is useless. But it can be used to do an exhaustive check:
;
The function reactToSemaphore
will fail in runtime if passed another value than 'red' | 'yellow' | 'green'
, but also with statically check that you aren't missing a case
in the switch
statement.
You can read more about the use of never
here.
contract
builders
optional
<T> (IContract<T>) -> IContract<T | undefined>
Takes a contract
and returns a new one that matches like the first one but also matches undefined
values.
;// All the following are valid:optionalNumber9;optionalNumberundefined;optionalNumber;
nullable
<T> (IContract<T>) -> IContract<T | null>
Takes a contract
and returns a new one that matches like the first one but also matches null
values.
;// The following are validnullableNumber9;nullableNumbernull;
oneOf
(...(string | number | boolean)[]) -> IContract<union of valid values>
It is used to validate unum
-like values. You specify the valid values and it returns a contract
that will check against them. Example:
;; // os's type is 'Linux' | 'Mac OS' | 'Windows' | 'Other'
TypeScript will infere the contract
's return value as the union of the literal types passed (up to 10 parameters, then behaves like <T extends string | number | boolean> IContract<T>
).
union
...(IContract) _> IContract<union of valid values>
It takes contracts as arguments and returns a new contract that matches if any of the them matches.
;numOrStr9;numOrStr'nine';
TypeScript will infere the contract
's return value as the union of the return values of the contracts passed (up to 10 parameters, then behaves like IContract<any>
).
arrOf
<T> (IContract<T>) -> IContract<T[]>
It takes a contract
"C
" as a parameter and returns another contract
that expects an array
of elements that match C
.
;;
objOf
<T> (IMapOfContracts<T>) -> IContract<T>
Takes an object that describes the shape of the objects
you want to validate and returns a contract
with that validation. That object's values must be contracts
.
;// <3;
strictObjOf
<T> (IMapOfContracts<T>) -> IContract<T>
It is the same than objOf
function, but also checks that the target doesn't have extra properties.
// It only matches empty objects;;
instanceOf
<C> (constructor: C) -> IContract<I>
(I
is instance of C
)
It takes a class or a or a constructor function and returns a contract
of instances of that class or constructor.
;;
Credits
Made from the typescript-library-starter
.
Thanks goes to these wonderful people:
Gonzalo Gluzman 💻 📖 ⚠️ 💡 |
Hernan Rajchert 📖 💻 |
Cristhian Duran 💻 📖 💡 ⚠️ |
Nicolás Quiroz 📖 |
---|
This project follows the all-contributors specification. Contributions of any kind welcome!