1.0.0 • Published 3 months ago
typeguard-ts v1.0.0
typeguard-ts
Description
typeguard-ts
is a utility library for creating and using type guards efficiently in TypeScript. It simplifies the process of defining and applying type guards, making it more convenient and readable in your codebase.
Installation
You can install the package using npm:
npm install typeguard-ts
Usage Example
Creating a Type Guard
import { createTypeGuard } from "typeguard-ts";
type Animal = { name: string };
const isAnimal = createTypeGuard<Animal>("name");
if (isAnimal({ name: "Lion" })) {
const animal: Animal = { name: "Lion" };
}
Combining Type Guards
import { createTypeGuard, combineTypeGuards } from "typeguard-ts";
type Car = { brand: string };
type Bike = { type: string };
const isCar = createTypeGuard<Car>("brand");
const isBike = createTypeGuard<Bike>("type");
const isVehicle = combineTypeGuards<Car | Bike>(isCar, isBike);
const vehicle: Car | Bike = { brand: "Toyota" };
if (isVehicle(vehicle)) {
const { brand } = vehicle;
}
Handling Arrays
import { createTypeGuard, filterArray } from "typeguard-ts";
type Person = { name: string };
const isPerson = createTypeGuard<Person>("name");
const people: (Person | string)[] = [
{ name: "John" },
"Invalid",
{ name: "Alice" },
];
const validPeople = filterArray<Person>(people, isPerson);
Promising Field
As TypeScript gains more popularity, having a utility library that facilitates working with type guards can be highly beneficial. This package addresses a fundamental aspect of TypeScript development, promoting better type safety and code readability.
License
This project is licensed under the MIT License - see the LICENSE file for details.
1.0.0
3 months ago