ype
This project is still in its experimental stages.
TypeScript is cool, but it only gives you static type checking. Type errors can still slip into your code. Ype is designed to give you runtime type assertions in JavaScript, with minimal performance overhead and helpful error messages.
You can use Ype anywhere you need to, but the major use case Ype was built for is in function arguments.
Why TypeScript (or any other static typechecker) isn't enough
TypeScript statically checks your code for possible type errors. But it cannot stop all errors, especially if you type wrongly or weakly (which happens more than we like to admit).
Look at this piece of valid TypeScript code. It gets a value from the user (form submission) and does something with it.
;performActionaction;
But you have no way of stopping the user from passing in a different value for action
, without added frontend validation not covered by TypeScript. This can lead to bugs in your code (deleteThing()
will be called unintentionally). With ype, you can prevent such with runtime assertions.
Examples
const y = ; { ; // Continue with the rest of your code. // At this point, `userId` will definitely be a Number, // so if you do userId + 1, you won't see nonsense like "undefined1"} ; // This is OK; // This will throw, because "one" is not a number
You can have nullable types, union types and more:
const y = ; { ;} ; // This is OK; // This is OK; // This is OK; // This will throw
More:
// Going further { ;} // define and reuse typesconst UserType = yshape id: Number name: String; const PinCodeType = y; // then use: { ; // save the PIN} // Will throw error: 'hahaha' is the wrong type. // Expected a PIN code (4-digit string), but got 'hahaha' (6 digits).; // Will throw error: 8 is the wrong type. // Expected a PIN code (4-digit string), but got number.; // Will throw error: '6d44' is of the wrong type. // Expected a PIN code (4-digit string), but got a non-digit 'd';