What is @glideapps/ts-necessities?
@glideapps/ts-necessities is a utility library for TypeScript that provides a collection of essential types and utility functions to simplify common tasks and improve type safety in TypeScript projects.
What are @glideapps/ts-necessities's main functionalities?
Optional
The `Optional` type allows you to define a type that can either be a specific type or `null` or `undefined`. This is useful for handling optional values in a type-safe manner.
import { Optional } from '@glideapps/ts-necessities';
function getLength(str: Optional<string>): number {
return str ? str.length : 0;
}
console.log(getLength('hello')); // 5
console.log(getLength(null)); // 0
NonEmptyArray
The `NonEmptyArray` type ensures that an array has at least one element. This is useful for functions that require a non-empty array as input.
import { NonEmptyArray } from '@glideapps/ts-necessities';
function getFirstElement(arr: NonEmptyArray<number>): number {
return arr[0];
}
console.log(getFirstElement([1, 2, 3])); // 1
assertNever
The `assertNever` function is used in exhaustive type checking. It ensures that all possible cases in a union type are handled, and if not, it throws a compile-time error.
import { assertNever } from '@glideapps/ts-necessities';
type Shape = 'circle' | 'square';
function getArea(shape: Shape): number {
switch (shape) {
case 'circle':
return Math.PI * 1 * 1;
case 'square':
return 1 * 1;
default:
return assertNever(shape);
}
}
console.log(getArea('circle')); // 3.141592653589793
Other packages similar to @glideapps/ts-necessities
fp-ts
fp-ts is a library for functional programming in TypeScript. It provides a wide range of utilities for working with functional programming concepts, such as monads, functors, and applicatives. Compared to @glideapps/ts-necessities, fp-ts offers a more comprehensive set of functional programming tools and abstractions.
io-ts
io-ts is a runtime type system for IO decoding/encoding in TypeScript. It allows you to define codecs for validating and decoding data at runtime. While @glideapps/ts-necessities focuses on utility types and functions, io-ts is specialized in runtime type validation and decoding.
utility-types
utility-types is a collection of utility types for TypeScript. It provides a variety of type transformations and utility types to enhance type safety and reduce boilerplate. Similar to @glideapps/ts-necessities, it aims to simplify common TypeScript tasks but with a broader range of utility types.
TS Necessities
These are some very basic functions and classes that we use at Glide to make coding with TypeScript easier and safer.
Installation
To add the package to your own project:
$ npm install @glideapps/ts-necessities