Gathering detailed insights and metrics for ts-dynamic-type-checker
Gathering detailed insights and metrics for ts-dynamic-type-checker
Gathering detailed insights and metrics for ts-dynamic-type-checker
Gathering detailed insights and metrics for ts-dynamic-type-checker
TypeScript library that performs dynamic type checking. It's useful for cases where you can't use TypeScript's static type checking (like reading a JSON object from a file).
npm install ts-dynamic-type-checker
Typescript
Module System
Min. Node Version
Node Version
NPM Version
73.6
Supply Chain
98.5
Quality
75.6
Maintenance
100
Vulnerability
100
License
TypeScript (100%)
Total Downloads
19,753
Last Day
2
Last Week
17
Last Month
35
Last Year
440
MIT License
8 Stars
43 Commits
2 Forks
1 Watchers
1 Branches
4 Contributors
Updated on Oct 26, 2023
Minified
Minified + Gzipped
Latest Version
0.0.13
Package Id
ts-dynamic-type-checker@0.0.13
Size
2.40 MB
NPM Version
4.2.0
Node Version
7.8.0
Cumulative downloads
Total Downloads
Last Day
0%
2
Compared to previous day
Last Week
0%
17
Compared to previous week
Last Month
-50.7%
35
Compared to previous month
Last Year
2.3%
440
Compared to previous year
29
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:
1import { readFile } from 'fs'; 2 3interface IAwsConfig { 4 // definitions... 5}; 6 7readFile('./my-aws-config.json', { encoding: 'utf8' }, (err, awsConfigStr) => { 8 if (err) { 9 console.error(err); 10 return; 11 } 12 const awsConfig: IAwsConfig = JSON.parse(awsConfigStr); 13});
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.
1npm install --save ts-dynamic-type-checker
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
:
1import { str } from 'ts-dynamic-type-checker'; 2 3str('Hello world'); // <- Returns 'Hello world' 4str(8 as any); // <- Throws a TypeError
1import { oneOf } from 'ts-dynamic-type-checker'; 2import { createInterface } from 'readline'; 3 4const isFruit = oneOf('apple', 'banana', 'strawberry', 'orange'); 5type IFruit = 'apple' | 'banana' | 'strawberry' | 'orange'; 6 7const readLine = createInterface({ 8 input: process.stdin, 9 output: process.stdout 10}); 11 12const aFruit: IFruit = 'cheese'; // <- static error. It will be warned by TypeScript itself. 13 14readLine.question('Which is your favourite fruit?', (someFruit) => { 15 const favouriteFruit: IFruit = isFruit(someFruit); // <- Will throw a TypeError if `someFruit` has any other value than 'apple', 'banana', 'strawberry' or 'orange'. It's a potential dynamic error and TypeScript could not detect it. 16});
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
:
1import { arrOf, num, oneOf } from 'ts-dynamic-type-checker'; 2 3const onlyNumbers = arrOf(num); 4 5onlyNumbers([1, 2, 3]); // <- Returns [1, 2, 3] 6onlyNumbers(['Hello', 'world', 99] as any); // <- Throws a TypeError 7 8const onlyHobbits = arrOf(oneOf('Frodo', 'Bilbo', 'Merry', 'Pippin', 'Sam', 'Gollum')); 9 10onlyHobbits(['Bilbo', 'Sam']); // <- Returns the array 11onlyHobbits(['Frodo', 'Pippin', 'Gandalf']); // <- 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:
1import { objOf, bool, str, num, arrOf } from 'ts-dynamic-type-checker'; 2 3const personValidator = objOf({ 4 name: str, 5 age: num, 6 profession: oneOf('student', 'employed', 'unemployed', 'retired'), 7 address: objOf({ 8 street: str, 9 city: str, 10 state: str, 11 country: str 12 }), 13 driving_license: bool 14}); 15 16const peopleValidator = arrOf(personValidator); 17 18// xhr function from any library you like 19xhr('/URI/to/people') 20 .then(peopleValidator) 21 .then(people => /* 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.
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:
1import { str, num, objOf } from 'ts-dynamic-type-checker'; 2 3str(9); // TypeScript will error ("string expected"). 4const aNumber = num(9); // TypeScript will infere it's a number. 5 6const fooBarContract = objOf({ 7 foo: str, 8 bar: num 9}); 10 11fooBarContract({ 12 baz: 'Hello' 13}); // <- Typescript will error 14 15const fooBar = fooBarContract({ 16 foo: 'Hello', 17 bar: 100 18}); // <- TypeScript will infer type {foo: string; bar: number;}
contracts
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
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:
1const objHasFooContract = objOf({ 2 foo: anything 3});
never
You may think the never
contract is useless. But it can be used to do an exhaustive check:
1const reactToSemaphore = (semaphoreLight: 'red' | 'yellow' | 'green') => { 2 switch (semaphoreLight) { 3 case 'red': 4 return 'stop'; 5 case 'yellow': 6 return 'hurry'; 7 case 'green': 8 return 'go'; 9 default: 10 never(semaphoreLight); 11 } 12};
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
buildersoptional
<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.
1const optionalNumber = optional(num); 2// All the following are valid: 3optionalNumber(9); 4optionalNumber(undefined); 5optionalNumber();
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.
1const nullableNumber = nullable(num); 2// The following are valid 3nullableNumber(9); 4nullableNumber(null);
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:
1const osContract = oneOf('Linux', 'Mac OS', 'Windows', 'Other'); 2const os = osContract('Linux'); // 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.
1const numOrStr = union(num, str); 2numOrStr(9); 3numOrStr('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
.
1const arrOfNumbersContract = arrOf(num); 2const numbers = arrOfNumbersContract([1, 2, 3]);
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
.
1const petContract = objOf( 2 name: str, 3 species: oneOf('dog', 'cat', 'golden fish', 'parrot', 'other'), 4 age: number, 5 gender: oneOf('male', 'female') 6); 7// <3 8const oddy = petContract({ 9 name: 'Oddy', 10 species: 'dog', 11 age: 8, 12 gender: 'female' 13});
strictObjOf
<T> (IMapOfContracts<T>) -> IContract<T>
It is the same than objOf
function, but also checks that the target doesn't have extra properties.
1// It only matches empty objects 2const emptyObjectContract = strictObjOf({}); 3const emptyObject = emptyObjectContract({});
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.
1class Foo {} 2 3const instanceOfFooContract = instanceOf(Foo); 4const foo = instanceOfFooContract(new Foo());
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!
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 2/26 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
84 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-06-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More