Nightingale Posing Mischievously

npm

Need private packages and team management tools?Check out npm Orgs. »

typeguard-generator

1.0.3 • Public • Published

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 {
    [propertystring]: IInterfaceProperty;
}
 
export interface IInterfaceProperty {
    // assumed required by default
    typepropertyType;
    optional?: boolean;
}
 
export type propertyType = 'string' | 'boolean' | 'number' | 'any' | IInterfaceDefinition;

install

npm i typeguard-generator

Downloadsweekly downloads

1

version

1.0.3

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability