JSPM

typeguard-generator

1.0.3
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2
  • Score
    100M100P100Q27617F
  • License MIT

An easy way to create typescript interface type guards

Package Exports

  • typeguard-generator

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (typeguard-generator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

typeguard-generator

This is an npm module designed to make it easy to create type guards for an interface.

Usage

npm i typeguard-generator

import * as generator from 'typeguard-generator';

To creare a typeguard you must describe its properties with an interface

interface IMyInterface {
    propA: string;
    propB?: number;
}

let myInterface: generator.IInterfaceDefinition = {
    propA: {
        type: 'string',
    },
    propB: {
        type: 'number', 
        optional: true,
    }
}

then use the generateGuard function to create the typeguard

let myInterfaceGuard: (test: any) => test is IMyInterface = generator.generateGuard<IMyInterface>(myInterface);

let test1: any = {
    propA: 'here',
};

let test2: any = {
    propA: 'here',
    propB: 8,
};


let test3: any = {};
let test4: any = {
    propA: 5,
};

// true, cast as IMyInterface
myInterfaceGuard(test1);
myInterfaceGuard(test2);
// false 
myInterfaceGuard(test3);
myInterfaceGuard(test4);

The features of the generator are limited at this point, the IInterfaceDefinition should make what is and is not support clear

export interface IInterfaceDefinition {
    [property: string]: IInterfaceProperty;
}

export interface IInterfaceProperty {
    // assumed required by default
    type: propertyType;
    optional?: boolean;
}

export type propertyType = 'string' | 'boolean' | 'number' | 'any' | IInterfaceDefinition;