0.1.2 • Published 3 months ago

guarantee-type v0.1.2

Weekly downloads
-
License
-
Repository
github
Last release
3 months ago

guarantee-type

guarantee the type of a plain object

designing npm-version build coverage outdated-deps

language: English also available in: Spanish

Main goal

When we use Typescript, in some point we want to use types everywere. But in some cases is very dificult to avoid the use of any.

For example, when we get data from LocalStorage, we transfer data in the network or we retieve from the database and ower ORM is no typed enought.

type Person = {
    name: string,
    age?: number,
    active: boolean,
    due: Date
};

function print(person: Person){
    // ...
};

print(JSON.parse(localStorage['person1'])) // 💩 receiving any

// Using https://node-postgres.com/
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].messagggge)  // 💩 receiving undefined because the typo

Currently Typescript do not avoid the use of any in the right hand of an assignation. But regardless of that we need a way to validate and set types of received data.

import { guarantee, is, GuaranteedType } from "guarantee-type";

var descriptionPerson = is.object({
    name: is.string,
    age: is.optional.number,
    active: is.boolean,
    due: is.class(Date)    // for Date class only you can write is.Date
});

type Person = GuaranteedType<typeof descriptionPerson>;

function print(person: Person){
    // ...
};

print(guarantee(descriptionPerson, JSON.parse(localStorage['person1']))); // 👍 ok, type guaranteed!

// Using https://node-postgres.com/
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(guarantee( is.object({message: is.string}), res.rows[0]).messagggge)  // 👍 ok, typo detected!

Deep into

Using is for describe the type is optional. The descriptions can be defined in a plain Javascript object that can be serializable and enceded with JSON. For example descriptionPerson can be writen like this:

var descriptionPerson = {
    object: {
        name: { string: {} },
        age: { optional: { number: {} },
        active: { boolean: {} },
        due: { class: Date }
    }
};

License

MIT

0.1.2

3 months ago

0.1.1

3 months ago

0.1.0

10 months ago

0.0.10

1 year ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.4

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago