Giter Site home page Giter Site logo

davidkarolyi / tguard Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 248 KB

Declarative type guarding system for TypeScript

Home Page: https://www.npmjs.com/package/tguard

License: MIT License

TypeScript 99.34% JavaScript 0.66%
typescript typeguard typesafety types typevalidator

tguard's Introduction

tguard ๐Ÿ’‚

Declarative type guarding system for TypeScript.

CI codecov

Installation

npm install tguard

or

yarn add tguard

Example Usage

import {
  TArray,
  TInteger,
  TObject,
  TString,
  TStringUUID,
  GuardedType,
} from "tguard";

// Let's define a User type as a Guard.
const TPost = TObject({
  id: TStringUUID,
  title: TString,
  body: TString,
});

const TUser = TObject({
  id: TStringUUID,
  name: TString,
  age: TInteger,
  posts: TArray(TPost),
});

// Note: If you don't want to define these types twice
// (once as a TypeScript type, once as a guard)
// you can infer it's guarded types with the `GuardedType` utility type:
type User = GuardedType<typeof TUser>;
type Post = GuardedType<typeof TPost>;

// We can use guards to validate if a given value is a valid 'User' type or not:
if (TUser.isValid(unknownValue)) {
  // TypeScript will know that `unknownValue` is 'User' in this block.
}

// Or try to cast a value to the User type:
try {
  const user = TUser.cast({ posts: ["Who am I?", "I am a user."] });
  // Type of `user` === {
  //    id: string,
  //    name: string,
  //    age: number,
  //    posts: Array<{id: string, title: string, body: string}>
  // }
} catch (error) {
  // error.message === 'Validation failed: Missing value at "id", expected type: string(UUID)'
}

Motivation, Guarding Types Manually โŒ

TypeScript does a static analysis to infer types, but won't provide any guarantees for runtime type safety. These checks should be done by the developer manually.

Here is an example for that with using type predicates:

โŒ Without tguard:

interface User {
  name: string;
  posts: string[];
}

function isUser(fetchedUser: any): fetchedUser is User {
  const user = fetchedUser as User;
  return typeof user.name === "string" && isStringArray(user.posts);
}

function isStringArray(array: any): array is string[] {
  if (!Array.isArray(array)) return false;
  for (const item of array) {
    if (typeof item !== "string") return false;
  }
  return true;
}

โœ… With tguard

import { TObject, TString, TArray } from "tguard";

const TUser = TObject({
  name: TString,
  posts: TArray(TString),
});

Guards

By convention, every guard's name starts with an upper-case T. These are instances of the Guard abstract class with a name field, isValid method, and a cast method.

Built-in type guards:

Primitive Guards

Functions, returning a Guard

Defining Custom guards

You can define any custom Guard with TValidate.

Defining a guard that validates if a number is bigger than 10:

const TNumberBiggerThan10 = TValidate<number>(
  "number(bigger than 10)",
  (value) => typeof value === "number" && value > 10
);

Exported utility tpyes

Tree shaking

All guards can be imported as a single module, which enables tree-shaking:

import TString from "tguard/lib/guards/TString";
import Guard, { GuardedType } from "tguard/lib/Guard";

tguard's People

Contributors

davidkarolyi avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.