TypeScript Total Functions
A collection of total functions to replace TypeScript's built-in partial functions.
Intended to be used with strictNullChecks enabled.
Installation
# yarn yarn add total-functions # npm npm install total-functions
The Functions
get
(type-safe array index operator)
The array index operator is not well-typed in TypeScript:
;; // b has type object, not object | undefined as you might expectb.toString; // boom ;; // bar has type string, not string | undefinedbar.toUpperCase; // boom
get
is a safe alternative:
; ; // b has type object | undefined ; // bar has type string | undefined
Note that get
will exclude undefined
from the return type when there is enough type information to be confident that the result cannot be undefined. See the object and tuple examples below for examples where undefined
is not included in the return type.
More usage examples:
// tuple;; // 2; // undefined; // undefinedxs.mapx /* 1 | 2 | 3 */; // array;; // number | undefined; // number | undefinedys.mapy /* number */; // sparse array;; // number | undefined; // number | undefinedzs.mapz /* number | undefined */; // readonly array;; // 1 | 2 | 3 | undefined; // 1 | 2 | 3 | undefined // record;; // string | undefined; // string | undefined // object;; // string; // doesn't compile // const object;; // "asdf"; // doesn't compile
ESLint
There's also a corresponding ESLint rule to ban the unsafe array index operator.
See https://github.com/danielnixon/eslint-plugin-total-functions