typescript-is-type
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

typescript-is-type

A TypeScript-safe runtime type check function

Build Status Build Cron Coverage Status Mutation testing badge Renovate enabled TypeScript

Network requests responses or JSON based data doesn't allow TypeScript to perform compile-time checks. You can cast the response but it doesn't give you the confidence that the data is an instance of the desired type.

This simple one-function package allows you to perform both TypeScript-safe and runtime-safe data check.

If one of the keys to be checked is undefined than the check doesn't pass (it's not based on hasOwnProperty).

# isntall it with
npm install --save-dev typescript-is-type
is<string>("Hello world", "length"); // true
is<string>("Hello world", "concat"); // TS compile error, "concat" isn't a key of string
is<string>(JSON.parse(JSON.stringify("Hello world")), "length"); // true

That's the function signature

function is<Type>(instance: any, keys: keyof Type|(keyof Type)[]): instance is Type

A more explanatory example

import { is } from 'typescript-is-type';

interface Car {
  power: number
}
interface FuelCar extends Car {
  tank:number
}
interface ElectricCar extends Car {
  battery:number
  singlePedalDrive: boolean
}

is<ElectricCar>(JSON.parse(JSON.stringify({
  power: 450,
  tank: 60
})), "battery") // false

Remember that it's up to you to decide the keys to be checked to avoid every false positive/negative.

is<ElectricCar>({
  power: 450,
  tank: 60
}), "power") // true 🤔
is<ElectricCar>({
  power: 450,
  tank: 60
}), ["power", "battery"]) // false 🎉

Contributors

Thanks goes to these wonderful people (emoji key):

Stefano Magni
Stefano Magni

💻 ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

Readme

Keywords

none

Package Sidebar

Install

npm i typescript-is-type

Weekly Downloads

12

Version

1.0.2

License

MIT

Unpacked Size

692 kB

Total Files

18

Last publish

Collaborators

  • noriste