Package Exports
- primitive-predicates
- primitive-predicates/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (primitive-predicates) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
primitive-predicates
A simple TypeScript library providing type guards for the primitive types in JavaScript.
What is it?
TypeScript will use certain clues to narrow the typing information down as much as it can before runtime. To help the compiler do this, TypeScript provides two features that this library uses to provide convenience functions:
- Type predicate functions
- Type assertion functions
Predicates
Type predicate functions take in
an argument, and return a boolean that is true
if the passed argument was the expected type, or false
if it isn't.
For example:
import { isString } from "primitive-predicates";
function doSomething(myArg: string): number;
function doSomething(myArg: number): string;
function doSomething(myArg: any): number | string {
if (isString(myArg)) {
return 42;
}
return "you gave me a number";
}
const aNumber = doSomething("definitely a string"); // The compiler will know 'aNumber' is a number.
const aString = doSomething(3); // The compiler will know 'aString' is a string.
Assertions
Type assertion functions work much the same way as predicates, except they throw an error if the argument passed isn't of the expected type. This is particularly useful when you're pretty sure something is a given type but you don't wanna have to mess around with flow control. Simply plop an assertion down and everything after it assumes the value is that type.
For example:
import { assertIsString } from "primitive-predicates";
function printUppercase(myArg: any) {
assertIsString(myArg);
console.log(myArg.toUppercase()); // compiler doesn't complain
}