TypeScript Definition Utilities

0.0.14 · maintenance · verified Tue Apr 21

tsdef is a TypeScript utility library that provides a curated collection of common type definitions and aliases to simplify complex type patterns and enhance code readability in TypeScript projects. It aims to reduce boilerplate and improve type safety by offering widely applicable utility types such as `Nullable`, `NonNull`, `MaybePromise`, and various `Props` modifiers (e.g., `NonNullProps`, `WritableProps`). The current stable version is 0.0.14. As a pre-1.0 release, its release cadence is likely irregular, and breaking changes might occur more frequently than with a semantically versioned stable library. It differentiates itself by being a pure type-only library, meaning it introduces zero runtime overhead and focuses exclusively on type-system improvements, making it suitable for projects that prioritize strict type integrity without adding to the JavaScript bundle size.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the usage of `Nullable`, `NonNull`, `MaybePromise`, and `MaybeArray` type utilities from `tsdef` to handle common TypeScript type patterns, showcasing how to define types that explicitly allow or disallow null/undefined, or encapsulate potential promises or arrays.

import { Nullable, NonNull, MaybePromise, MaybeArray } from 'tsdef';

// Define a string that can also be null or undefined
const nullableString: Nullable<string> = 'hello';
const anotherNullableString: Nullable<string> = null; // This is OK
// const invalidNullableString: Nullable<string> = undefined; // Also OK if 'nil' includes undefined

// Define a string that explicitly cannot be null
const nonNullString: NonNull<string | null> = 'world';
// const invalidNonNullString: NonNull<string | null> = null; // Type error: Type 'null' is not assignable to type 'string'.

// Define a value that might be a promise or the value itself
type User = { id: string; name: string };
const getUserSync = (): User => ({ id: '1', name: 'Alice' });
const getUserAsync = (): Promise<User> => Promise.resolve({ id: '2', name: 'Bob' });

const maybePromiseUser: MaybePromise<User> = getUserSync();
const anotherMaybePromiseUser: MaybePromise<User> = getUserAsync();

// Define a value that might be a single item or an array of items
const singleItem: MaybeArray<string> = 'item';
const multipleItems: MaybeArray<string> = ['item1', 'item2'];

console.log(nullableString); // Output: hello
console.log(nonNullString);  // Output: world

view raw JSON →