0.2.2 • Published 11 months ago
guarantee-type v0.2.2
guarantee-type
guarantee the type of a plain object
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 typoCurrently 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 }
}
};
also available in:
