TypeScript utility types for portable JavaScript libraries.
This package contains only types. Its imports are erased at build time and are safe to use in projects targeting browsers, Node, Deno, and Bun.
import type { Dict, MaybePromise } from "@rcompat/type";AbstractNewable#
An abstract constructor with configurable instance and argument types.
Type parameters
I— Constructed instance type.A— Constructor argument tuple.
type AbstractNewable<I = unknown, A extends any[] = any[]> =
abstract new (...args: A) => I;Arch#
CPU architectures recognized by rcompat runtime APIs.
type Arch = "x64" | "arm64";Bag#
A readable string-keyed value bag.
Type parameters
V— Stored value type.
interface Bag<V = string> {
// Returns a value or throws when its key is missing.
get(key: string): V;
// Returns a value or `undefined` when its key is missing.
try(key: string): V | undefined;
// Checks whether a key exists.
has(key: string): boolean;
// Iterates over key/value entries.
[Symbol.iterator](): IterableIterator<readonly [string, V]>;
// Returns all entries as a dictionary.
all(): Dict<V>;
// Returns a JSON-compatible dictionary representation.
toJSON(): Dict<V>;
// Returns the bag's string representation.
toString(): string;
}Boolish#
Boolean values represented as lowercase strings.
type Boolish = "false" | "true";DeepMutable#
Recursively removes readonly modifiers from arrays and objects.
Type parameters
T— Value type to make mutable.
type DeepMutable<T> =
T extends readonly [...infer E extends readonly unknown[]]
? { -readonly [K in keyof E]: DeepMutable<E[K]> }
: T extends Dict
? { -readonly [K in keyof T]: DeepMutable<T[K]> }
: T;Dict#
A string-keyed record.
Type parameters
V— Stored value type.
type Dict<V = unknown> = Record<string, V>;EmptyDict#
The inferred type of an empty object literal.
type EmptyDict = typeof _;ImpliedOptional#
Adds undefined when every property of an object accepts it.
Type parameters
T— Value type to inspect.
type ImpliedOptional<T> = AllOptional<T> extends true
? T | undefined
: T;Import#
A module namespace containing a default export.
type Import = { default: unknown } & Dict;IndexedKeys#
Tests whether a dictionary exposes concrete string or numeric keys.
Type parameters
T— Dictionary type to inspect.
type IndexedKeys<T extends Dict> =
Extract<keyof T, number | string> extends never ? false : true;IsAny#
Tests whether a type is any.
Type parameters
T— Type to inspect.
type IsAny<T> = false extends T & true ? true : false;IsArray#
Tests whether a type is a non-tuple array.
Type parameters
T— Type to inspect.
type IsArray<T> =
Some<[IsNever<T>, IsAny<T>]> extends true ? false :
[T] extends [readonly unknown[]]
? IsTuple<T> extends true ? false : true
: false;IsClass#
Tests whether a type is a non-static object instance.
Type parameters
T— Type to inspect.
type IsClass<T> =
Some<[
IsNever<T>,
IsAny<T>,
Is<T, Math>,
Is<T, JSON>,
Is<T, Atomics>,
]> extends true ? false :
T extends { constructor: unknown } & object
? true
: false;IsNever#
Tests whether a type is never.
Type parameters
T— Type to inspect.
type IsNever<T> = Is<T, never>;IsTuple#
Tests whether a type is a fixed-length tuple.
Type parameters
T— Type to inspect.
type IsTuple<T> =
[T] extends [readonly [...infer Elements]]
? number extends Elements["length"]
? false
: true
: false;IsUnion#
Tests whether a type is a union.
Type parameters
T— Type to inspect.
type IsUnion<T> = (
T extends unknown
? (x: T) => void
: never
) extends (x: infer U) => void
? [T] extends [U]
? false
: true
: never;IsUnknown#
Tests whether a type is exactly unknown.
Type parameters
T— Type to inspect.
IsVoid#
Tests whether a type is exactly void.
Type parameters
T— Type to inspect.
type IsVoid<T> = Is<T, void>;Join#
Joins a tuple of string types with a separator.
Type parameters
T— Strings to join.Separator— Separator placed between strings.
type Join<T extends string[], Separator extends string = ", "> =
T extends [] ? "" :
T extends [infer First extends string] ? First :
T extends [infer First extends string, ...infer Rest extends string[]]
? `${First}${Separator}${Join<Rest, Separator>}` : string;JSONPointer#
An empty or slash-prefixed JSON Pointer path.
type JSONPointer = "" | `/${string}`;JSONValue#
A value representable in JSON.
type JSONValue =
| { readonly [key: string]: JSONValue }
| JSONPrimitive
| readonly JSONValue[];LooseOptional#
Makes properties accepting undefined optional while retaining explicit
undefined in their value types.
Type parameters
T— Object type to transform.
type LooseOptional<T> = Unpack<
{ [K in keyof T as Undef extends T[K]
? K
: never]?: Exclude<T[K], Undef> | undefined; } &
{ [K in keyof T as Undef extends T[K] ? never : K]: T[K]; }
>;Maybe#
A value that may be undefined.
Type parameters
T— Defined value type.
type Maybe<T> = T | undefined;MaybePromise#
A synchronous value or a promise for that value.
Type parameters
T— Resolved value type.
type MaybePromise<T> = Promise<T> | T;Mutable#
Removes top-level readonly modifiers.
Type parameters
T— Value type to make mutable.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };Newable#
A concrete constructor with configurable instance and argument types.
Type parameters
I— Constructed instance type.A— Constructor argument tuple.
type Newable<I = unknown, A extends any[] = any[]> = new (...args: A) => I;Not#
Negates a boolean literal type.
Type parameters
T— Boolean to negate.
type Not<T extends boolean> = T extends true ? false : true;Nullish#
A null or undefined value.
type Nullish = null | undefined;OS#
Operating-system names recognized by rcompat runtime APIs.
type OS = "linux" | "darwin" | "windows";PackageJSON#
A typed npm-compatible package.json manifest.
type PackageJSON = {
name: string;
version: string;
description?: string;
keywords?: string[];
homepage?: string;
bugs?: string | {
url?: string;
email?: string;
};
license?: string;
author?: Person;
contributors?: Person[];
funding?: Funding | Funding[];
files?: string[];
exports?: string | string[] | JSONValue;
imports?: JSONValue;
main?: string;
type?: "module" | "commonjs";
browser?: string;
bin?: string | JSONValue;
man?: string | string[];
directories?: JSONValue;
repository?: string | TypeURL & { directory?: string };
scripts?: JSONValue;
gypfile?: boolean;
config?: JSONValue;
dependencies?: JSONValue;
devDependencies?: JSONValue;
peerDependencies?: JSONValue;
peerDependenciesMeta?: Dict<{ optional: boolean }>;
bundleDependencies?: string[] | boolean;
bundledDependencies?: string[] | boolean;
optionalDependencies?: JSONValue;
overrides?: JSONValue;
engines?: JSONValue;
os?: string[];
cpu?: string[];
libc?: string[];
devEngines?: JSONValue;
private?: boolean;
publishConfig?: JSONValue;
workspaces?: string[];
};PartialDict#
A string-keyed record whose values may be absent.
Type parameters
T— Defined value type.
type PartialDict<T> = Dict<T | undefined>;Primitive#
Any JavaScript primitive value.
type Primitive = bigint | boolean | null | number | string | symbol | undefined;Print#
Converts a TypeScript type into a readable string literal type.
Type parameters
T— Type to print.
type Print<T> =
IsVoid<T> extends true ? "void" :
IsUnknown<T> extends true ? "unknown" :
IsNever<T> extends true ? "never" :
IsAny<T> extends true ? "any" :
[T] extends [boolean] ? [boolean] extends [T] ? "boolean" : `${T}` :
IsUnion<T> extends true ? PrintUnion<T> :
T extends string ? string extends T ? "string" : `'${T}'` :
T extends number ? number extends T ? "number" : `${T}` :
T extends bigint ? bigint extends T ? "bigint" : `${T}n` :
T extends symbol ? "symbol" :
T extends null ? "null" :
T extends undefined ? "undefined" :
IsTuple<T> extends true ? PrintTuple<T> :
IsArray<T> extends true ?
T extends (infer E)[] ? `${PrintArray<E>}[]` :
T extends ReadonlyArray<infer E> ? `readonly ${Print<E>}[]` : "array" :
T extends Dict ?
// If T is a fully readonly, concrete object (like Readonly<{ ok: boolean }>),
// print it wrapped as Readonly<...>. Otherwise print the dictionary normally.
IsEqual<T, Readonly<T>> extends true ?
HasSpecificKeys<T> extends true ?
`Readonly<${PrintDict<Mutable<T>>}>` :
PrintDict<T> :
PrintDict<T> :
IsClass<T> extends true ? PrintClass<T> :
never
;Printable#
A value carrying a readable type name.
interface Printable {
// The readable type name.
readonly Name: string;
}PrintableGeneric#
A printable value carrying its represented type.
Type parameters
Type— Represented type.
interface PrintableGeneric<Type> extends Printable {
// The represented type marker.
readonly Type: Type;
}Schema#
A parser that converts unknown input into a typed value.
Type parameters
T— Parsed output type.
interface Schema<T> {
// Parses and validates an unknown input.
parse(input: unknown): T;
}Serializable#
A value with a custom JSON-compatible representation.
JSON.stringify invokes toJSON when serializing implementations.
interface Serializable {
// Converts the value into a JSON-compatible representation.
toJSON(): JSONValue;
}Some#
Tests whether any member of a boolean tuple is true.
Type parameters
T— Boolean tuple to inspect.
type Some<T extends readonly boolean[]> =
T extends readonly [infer First, ...infer Rest extends boolean[]]
? First extends true ? true : Some<Rest>
: false
;StringClass#
A string-like object supporting replacement and conversion.
type StringClass = {
[Symbol.replace](string: string, replacement: string): string;
[Symbol.replace](string: string, replacement: StringReplacer): string;
toString(): string;
};StringLike#
A primitive string or string-like object.
type StringLike = string | StringClass;StringReplacer#
A replacement callback accepted by String.prototype.replace.
type StringReplacer = ((substring: string, ...params: any[]) => string);TupleToUnion#
Converts a tuple into a union of its element types.
Type parameters
T— Tuple to convert.
type TupleToUnion<T extends readonly unknown[]> = T[number];TypedArray#
Any JavaScript typed array.
Type parameters
Buffer— Allowed backing buffer type.
type TypedArray<Buffer extends ArrayBufferLike = ArrayBuffer> =
| BigInt64Array<Buffer>
| BigUint64Array<Buffer>
| Float16Array<Buffer>
| Float32Array<Buffer>
| Float64Array<Buffer>
| Int16Array<Buffer>
| Int32Array<Buffer>
| Int8Array<Buffer>
| Uint16Array<Buffer>
| Uint32Array<Buffer>
| Uint8Array<Buffer>
| Uint8ClampedArray<Buffer>
;UndefinedToOptional#
Makes properties accepting undefined optional and removes explicit
undefined from their value types.
Type parameters
T— Object type to transform.
type UndefinedToOptional<T> = Unpack<
{ [K in keyof T as Undef extends T[K] ? K : never]?: Exclude<T[K], Undef>; } &
{ [K in keyof T as Undef extends T[K] ? never : K]: T[K]; }
>;UnionToTuple#
Converts a union into a tuple containing each union member.
Type parameters
U— Union to convert.T— Accumulated tuple used during conversion.
type UnionToTuple<U, T extends unknown[] = []> = [U] extends [never]
? T
: UnionToTuple<Exclude<U, LastOf<U>>, [LastOf<U>, ...T]>
;UnknownFunction#
A callable function with arbitrary parameters and an unknown result.
type UnknownFunction = (...params: any[]) => unknown;UnknownMap#
A map with property keys and unknown values.
type UnknownMap = Map<PropertyKey, unknown>;UnknownSet#
A set containing unknown values.
type UnknownSet = Set<unknown>;Unpack#
Expands an object type for clearer editor display.
Type parameters
T— Object type to expand.
type Unpack<T> = { [K in keyof T]: T[K] } & {};