Utils
Utility functions for overiding TypeScript's default behaviour.
Errors
Utilities for managing Error objects.
getErrorMessage
Simplifies error handling in try...catch statements.
function getErrorMessage(error: unknown, fallbackMessage? string): stringJavaScript is weird, you can throw anythingβseriously, anything of any type.
try { someFunctionThatMightThrow();} catch (error) { Monitor.reportError(error.message); // ~~~~~ // Object is of type 'unknown'.}Type casting
Since it's possible for library authors to throw something unexpected, we have to take precautions. Using getErrorMessage takes care of type casting for you, and makes error handling safe and simple.
Monitor.reportError(getErrorMessage(error));// π No more TypeScript issues!Handles cases where the value isn't an actual Error object.
getErrorMessage({ message: 'Object text', other: () => 'Properties' });// β 'Object text'Supports a fallback message for "falsy" values.
getErrorMessage(undefined);// β 'Unknown error'getErrorMessage(undefined, 'Custom message text');// β 'Custom message text'Fails gracefully by stringifying unexpected values.
getErrorMessage({ msg: 'Something went wrong' });// β '{ "msg": "Something went wrong" }'Objects
Utility functions for objects.
typedEntries
An alternative to Object.entries() that avoids type widening.
Uses a type assertion which could be considered dangerous.
function typedEntries<T extends Record<string, unknown>>(value: T): ObjectEntry<T>[];Differences:
Object.entries({ foo: 1, bar: 2 });// β [string, number][]typedEntries({ foo: 1, bar: 2 });// β ['foo' | 'bar', number][]typedKeys
An alternative to Object.keys() that avoids type widening.
function typedKeys<T extends Record<string, unknown>>(value: T): Array<keyof T>;Differences:
Object.keys({ foo: 1, bar: 2 });// β string[]typedKeys({ foo: 1, bar: 2 });// β ("foo" | "bar")[]Example use case:
const obj = { foo: 1, bar: 2 };const thing = Object.keys(obj).map(key => { return obj[key]; // ~~~~~~~~ // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ foo: number; bar: number; }'. // No index signature with a parameter of type 'string' was found on type '{ foo: number; bar: number; }'.});
const thing2 = typedKeys(obj).map(key => { return obj[key]; // π No more TypeScript issues!});