https://github.com/noriste/typescript-is-type
A Typescript-safe runtime type check function
https://github.com/noriste/typescript-is-type
runtime-typechecking typescript
Last synced: 9 months ago
JSON representation
A Typescript-safe runtime type check function
- Host: GitHub
- URL: https://github.com/noriste/typescript-is-type
- Owner: NoriSte
- Created: 2019-02-28T07:52:32.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2023-06-03T10:17:25.000Z (over 2 years ago)
- Last Synced: 2025-03-14T20:39:57.615Z (10 months ago)
- Topics: runtime-typechecking, typescript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/typescript-is-type
- Size: 639 KB
- Stars: 3
- Watchers: 0
- Forks: 0
- Open Issues: 23
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# typescript-is-type
A TypeScript-safe runtime type check function
[](https://travis-ci.com/NoriSte/typescript-is-type)
[](https://travis-ci.com/NoriSte/typescript-is-type)
[](https://coveralls.io/github/NoriSte/typescript-is-type)
[](https://stryker-mutator.github.io)
[](https://renovatebot.com/)
[](https://codeclimate.com/github/NoriSte/typescript-is-type/maintainability)
[](https://github.com/ellerbrock/typescript-badges/)
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`).
```bash
# isntall it with
npm install --save-dev typescript-is-type
```
```typescript
is("Hello world", "length"); // true
is("Hello world", "concat"); // TS compile error, "concat" isn't a key of string
is(JSON.parse(JSON.stringify("Hello world")), "length"); // true
```
That's the function signature
```typescript
function is(instance: any, keys: keyof Type | (keyof Type)[]): instance is Type;
```
A more explanatory example
```typescript
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(
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.
```typescript
is({
power: 450,
tank: 60
}), "power") // true 🤔
is({
power: 450,
tank: 60
}), ["power", "battery"]) // false 🎉
```
## Contributors
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!