1.0.22 • Published 1 year ago

@tsdotnet/reflection v1.0.22

Weekly downloads
1
License
MIT
Repository
github
Last release
1 year ago

alt text tsdotnet / reflection

GitHub license npm-publish npm version

A set of classes and utilities for JavaScript type inspection and validation.

Docs

tsdotnet.github.io/reflection

TypeValidator<T>

Benefits

  • Allows for run-time validation and checking of dynamic types as well as integrated type-guarding.
  • Super easy to use, basically only requires a copy paste.
  • Works with literals!

Usage

Step 1: Declare the expected type/interface.

interface MyType
{
    a: object;
    b: string;
    c: number;
    d: boolean;
    e: {
        f: string;
        g: boolean;
        h: [
            number,
            boolean,
            string
        ];
    };
}

Step 2: Copy the interface as an actual object and <type> the validator

The following can be done with pure JavaScript and still work.

const myTypeValidator = new TypeValidator<MyType>(
{
    a: Object,
    b: String,
    c: Number,
    d: Boolean,
    e: {
        f: String,
        g: Boolean,
        h: [
            Number,
            Boolean,
            String
        ]
    }
});

Step 3: validate as many times as you want:

const myItem = {
    a: {},
    b: 'hello',
    c: 1,
    d: true,
    e: {
        f: 'whatever',
        g: false,
        h: [
            0,
            true,
            '2'
        ]
    },
    i: 'noise'
};

// no compile-time type errors!
if (MyTypeValidator.isSubsetOf(myItem)) {
    console.log(myItem.e.h.length); // 3
    console.log(myItem.b); // "hello"
} else {
    throw new TypeError('Invalid type!');
}
1.0.22

1 year ago

1.0.21

2 years ago

1.0.20

2 years ago

1.0.18

3 years ago

1.0.17

3 years ago

1.0.16

4 years ago

1.0.15

4 years ago

1.0.14

4 years ago

1.0.13

4 years ago

1.0.11

4 years ago

1.0.12

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago