An open API service indexing awesome lists of open source software.

https://github.com/veetaha/ts-typedefs

A handy collection of TypeScript plain and generic type definitions and interfaces.
https://github.com/veetaha/ts-typedefs

essentials type-level-programming types typescript typescript-definitions typescript-interfaces typescript-library

Last synced: 2 months ago
JSON representation

A handy collection of TypeScript plain and generic type definitions and interfaces.

Awesome Lists containing this project

README

        

ts-typedefs





---

[![npm version](https://badge.fury.io/js/ts-typedefs.svg)](https://badge.fury.io/js/ts-typedefs)
![npm](https://img.shields.io/npm/dm/ts-typedefs.svg?color=%2317c4b5)
[![Build Status](https://travis-ci.com/Veetaha/ts-typedefs.svg?branch=master)](https://travis-ci.com/Veetaha/ts-typedefs)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](https://www.typescriptlang.org/)

This library is a handy collection of TypeScript plain and generic type definitions and interfaces **for both frontend and backend**. You may expect **zero runtime overhead** if you use imported items only in
type contexts.

## [API documentation](https://veetaha.github.io/ts-typedefs/)
Generated by [typedoc](https://github.com/TypeStrong/typedoc)

## [Contribution guidelines](CONTRIBUTING.md)

## Credits
This project was inspired by ['ts-essentials'](https://github.com/krzkaczor/ts-essentials) library.
Some type names were taken from them.

## Quick API review
The most convenient way to explore `'ts-typedefs'` API is by easily browsing your *editor's completion
list* that shows signatures and descriptions for selected items. Types, functions, and classes names are intended to be super descriptive and intuitive.
All functional units provide *`typedoc` documentation in comments* so it is easy for
IDEs to provide you with good hints.

### Usage example
```ts
import { DeepPartial, FilterProps, Func, Op } from 'ts-typedefs';

class User { /* ... */ }
type UserData = FilterProps>;

function updateUser(userUpd: DeepPartial) { /* ... */ }
```

## Provided type definitions and runtime units

* [Objects](#objects)
* [`Obj<>`](#objtvalues-tkeys)
* [`Class<>`](#classtinstance-targs)
* [`InstanceType<> (with abstract classes support)`](#instancetypetclass)
* [`ValueOf<>`](#valueoftobj)
* [`RemoveKeys<>`](#removekeystsrcobj-tkeysunion)
* [`FilterProps<>`](#filterpropstobj-tapprovecond)
* [`[Deep]MapValues<>`](#mapvaluestsrcobj-tmappedvalue)
* [`Merge<>`](#mergetobj1-tobj2)
* [`[Deep]Partial/Required<>`](#deeppartialrequiredtobj)
* [`[Deep]Readonly/Mutable<>`](#deepreadonlymutabletobj)
* [`OptionalLikelyUndefProps<>`](#optionallikelyundefpropstobj)
* [`...`](https://veetaha.github.io/ts-typedefs/modules/_types_objects_.html)
* [Functions](#functions)
* [`[Async]Func<>`](#asyncfunctargs-tretval-tthis)
* [`AsyncFuncReturnType<>`](#asyncfuncreturntypetasyncfunc)
* [`...`](https://veetaha.github.io/ts-typedefs/modules/_types_functions_.html)
* [Decorators](#decorators)
* [`MethodDecorator<>`](#methoddecoratortargs-tretval-tmethnamelimit)
* [`PropertyDecorator<>`](#propertydecoratortproptype-tpropnamelimit)
* [`...`](https://veetaha.github.io/ts-typedefs/modules/_types_decorators_.html)
* [Logical](#logical)
* [`If<>`](#iftcond-tiftrue-telse-tifcondisbool)
* [`Not<>`](#nott-tiftisbool)
* [`And/Nand<>`](#andnandt)
* [`Or/Nor<>`](#ornort)
* [`[Not]Extends<>`](#notextendstextender-textendee)
* [`AreSame<>`](#aresamet1-t2)
* [`Is[Not]Any<>`](#isnotanytsuspect)
* [`Is[Not]Unknown<>`](#isnotunknowntsuspect)
* [`...`](https://veetaha.github.io/ts-typedefs/modules/_types_logical_.html)
* [Runtime](#runtime)
* [`reinterpret()`](#reinterprettvalue-any-t)
* [`class Debug.UnreachableCodeError`](#class-debugunreachablecodeerror)
* [`...`](https://veetaha.github.io/ts-typedefs/modules/_runtime_index_.html)
* [Misc](#misc)
* [`Tag<>`](#tagttarget-ttagname)
* [`UnionToIntersection<>`](#uniontointersectiontunion)
* [`UnpackPromise<>` ](#unpackpromisetpromise)
* [`PickAsOptional/Required/Readonly/Mutable/NullableProps<>`](#pickasoptionalrequiredreadonlymutablenullablepropstobj-tkeys)
* [`[Deep]Nullable<>`](#deepnullablet)
* [`Primitive`](#primitive)
* [`TypeName`](#typename)
* [`...`](https://veetaha.github.io/ts-typedefs/globals.html)

Let's see them in details.

## Objects

### [`Obj`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines an object with keys of type `TKeys`, and all values of `TValue` type.
```ts
type t0 = Obj; // { [key: string]: any; }
type t1 = Obj; // { [key: string]: boolean; }
type t2 = Obj; // { [key: number]: string; }
type t3 = Obj; // { p1: number, p2: number; }
```
### [`Class`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines constructor function type that instantiates `TInstance` and accepts arguments of `TArgs` type.

```ts
interface User { /* ... */ }

// new (...args: any) => User
type t0 = Class;

// new (...args: [string, number]) => User
type t1 = Class;
```

### [`InstanceType`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines an instance type of the given class or the type of its `prototype` property.
`TClass` may even be an abstract class, though those ones are not newable,
but the type of their instances can be obtained through their `prototype` property.

```ts
import { InstanceType } from 'ts-typedefs';

class User { id!: number; } // plain class

function getAbstractUser() {
abstract class AbstractUser { // local abstract class, its type is not
id!: number; // accessible in the global namespace
}
return AbstractUser;
}

type t0 = InstanceType; // User
type t1 = InstanceType>; // AbstractUser
```

### [`ValueOf`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines a union type of all the values stored in `TObj`.
```ts
interface User {
id: number;
login: string | null;
password: string;
isDisabled: boolean;
}
/* number | string | null | boolean */
type t0 = ValueOf;
/* union type of all properties and methods of `Array` */
type t1 = ValueOf;
```

### [`RemoveKeys`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines the same object type as `TSrcObj`, but without `TKeysUnion` keys.
```ts
interface User {
id: number;
login: string | null;
password: string;
isDisabled: boolean;
}
/*
{
id: number;
login: string | null;
isDisabled: boolean;
}
*/
type t0 = RemoveKeys;

/* { id: number; } */
type t1 = RemoveKeys;
```

### [`FilterProps`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines the same type as `TObj` but with particular properties filtered out according to `TApproveCond`. `TApproveCond` is a boolean operator tree structure that defines the criteria that the filtered values must match. All these operators are defined in `Op` namespace.

```ts
interface User {
id: number;
login: string | null;
password: string;
isDisabled: boolean;
flag: boolean;
}

/* { login: string; } */
type t0 = FilterProps>;

/*
{
isDisabled: boolean;
flag: boolean;
}
*/
type t0 = FilterProps>;

/*
{
isDisabled: boolean;
flag: boolean;
id: number;
}
*/
type t1 = FilterProps<
User,
Op.And<[
Op.Not>, // Op.UnionExcludes<> is another option
Op.Nand<[false, true, true, true]> // this condition is always true
]>
>;
```
Because of some TypeScript [limitations and bugs](https://stackoverflow.com/questions/55192212/typescript-circular-type-alias-produces-no-error-and-instead-widens-unit-types) `TApproveCond` tree must be not more than 5 levels deep (number of levels limitation may change, but it can only become greater).
### [`MapValues`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines the same object type as `TSrcObj`, but all values of `TMappedValue` type.
`DeepMapValues<>` variant maps values for all nested objects recursively.
```ts
interface User {
login?: string | null;
friend: {
friendliness: number;
ref: User;
}
}

/* { login: boolean; friend: boolean; } */
type t0 = MapValues;
/*
{
login: boolean;
friend: {
friendliness: boolean;
ref: DeepMapValues
}
}
*/
type t1 = DeepMapValues;

```

### [`Merge`](#provided-type-definitions-and-runtime-units "Go back to contents")
Merge objects `TObj1` and `TObj2`.
Properties types from `TObj2` override the ones defined on `TObj1`.
This type is analogous to the return type of `Object.assign()`

```ts
interface O1 {
p1: number;
p2: string;
p3: boolean;
}

interface O2 {
p2: number | null;
p3: string;
p4: O1;
}

/*
{
p1: number;
p2: number | null;
p3: string;
p4: O1;
}
*/
type t0 = Merge;

/*
{
p1: number;
p2: string;
p3: boolean;
p4: O1;
}
*/
type t1 = Merge;
```

### [`[Deep]Partial/Required`](#provided-type-definitions-and-runtime-units "Go back to contents")

`Partial/Required` defines the same type as `TObj` but
with all `TKeys` made optional/required.

`DeepPartial/Required<>` defines the same type as `TObj` but with all properties made recursively `Partial/Required<>`.

This two types are actually exactly opposite to each other.

```ts
interface User {
id: number;
name: {
first: string;
}
}

/*
{
id?: undefined | number;
name?: undefined | {
first: string;
}
}
*/
type PartUser = Partial;

/*
{
id?: number | undefined;
name?: undefined | {
first?: string | undefined;
};
}
*/
type DeepPartUser = DeepPartial;

type RequUser = Required; // User
type DeepRequUser = DeepRequired; // User
```

### [`[Deep]Readonly/Mutable`](#provided-type-definitions-and-runtime-units "Go back to contents")

`Readonly/Mutable` defines the same type as `TObj` but
with all `TKeys` made readonly/mutable.

`DeepReadonly/Mutable<>` defines the same type as `TObj` but with all properties made recursively `Readonly/Mutable<>`.

This two types are actually exactly opposite to each other.

```ts
interface User {
id: number;
name: {
first: string;
}
}

/*
{
readonly id: number;
readonly name: {
first: string;
}
}
*/
type RoUser = Readonly;

/*
{
readonly id: number;
readonly name: {
readonly first: string;
};
}
*/
type DeepRoUser = DeepReadonly;

type MutUser = Mutable; // User
type DeepMutUser = DeepMutable; // User
```

`DeepReadonly<>` is quite handy when you define deep readonly multidimensional arrays.

```ts
type t0 = DeepReadonly;
// readonly (readonly (readonly number[])[])[]
```

### [`OptionalLikelyUndefProps`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines the same type as `TObj`, but adds 'optional' modifier `?` to all
properties that allow `undefined` as their value type (this includes `unknown` and `any`).

```ts
interface User {
bio: string | undefined;
secret: unknown;
name: string;
}

/*
{
bio?: string | undefined;
secret?: unknown;
name: string; // notice may-not-be `undefined` props don't get '?' modifier
}
*/
type RepairedUser = OptionalLikelyUndefProps;
```

## Functions

### [`[Async]Func`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines a Function subtype with the given arguments, return type and `this` context. If it is `AsyncFunc<>` `TRetval` is packed into `Promise`

```ts
interface User { /* ... */ }

// (this: any, ...args: any) => unknown
type t0 = Func;

// (this: any, ...args: [string, number | undefined]) => unknown
type t1 = Func<[string, number | undefined]>;

// (this: any, ...args: [boolean]) => void
type t2 = Func<[boolean], void>;

// (this: User, ...args: [boolean]) => number
type t3 = Func<[boolean], number, User>;

// (this: any, ...args: [string]) => Promise
type t4 = AsyncFunc<[string], User>
```

### [`AsyncFuncReturnType`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines the unpacked result type of the `Promise` returned by the specified `TAsyncFunc`.

```ts
class User {
static async getById(id: number): Promise {
// ...
}
}

// User
type t0 = AsyncFuncReturnType>;

// User
type t1 = AsyncFuncReturnType
```

## Decorators

### [`MethodDecorator`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines a static or instance method decorator function type. `TArgs` tuple type limits the arguments' type decorated method accepts, `TRetval` limits the return type of the decorated method. `TMethNameLimit` defines the limitation for method names this decorator may be applied to.

```ts
declare function decor_any(): MethodDecorator;
declare function decor_bool(): MethodDecorator<[boolean]>;
declare function decor_getId(): MethodDecorator;

function decor_str$num_bool(): MethodDecorator<[string, number], boolean> {
// argument types are automatically deduced and strongly typed here
return (protoOrClass, methodName, propDescriptor) => {
/* (this: typeof protoOrClass, ...args: [string, number]) => boolean */
const val = propDescriptor.value;
// ...
};
};

class User {
@decor_getId() // compile error (method name mismatch)
@decor_bool() // compile error (params type mismatch)
@decor_str$num_bool() // compile error (params and return type mismatch)
@decor_any() // works fine
meth0(bol: boolean, num: number): void {}

@decor_any() // works fine
@decor_bool() // works fine
meth1(bol: boolean) {
return bol ? 32 : 'kek';
}

@decor_any() // works fine
@decor_str$num_bool() // works fine
meth2(str: string, num: number) {
return !!str && !!num;
}

@decor_getId() // works fine
getId() { }
}
```

### [`PropertyDecorator`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines a static or instance property decorator function type.

```ts
declare function decorateAny(): PropertyDecorator;
function decorateStr(): PropertyDecorator {
return /* function arguments are analogously deduced */;
};
function decorIdProp(): PropertyDecorator {
return /* function arguments are analogously deduced */;
};

export class User {
@decorIdProp() // compile error (prop name and value type mismatch)
@decorateStr() // works fine
@decorateAny() // works fine
prop0!: string;

@decorIdProp() // compile error (prop name mismatch)
@decorateStr() // compile error (prop value type mismatch)
@decorateAny() // works fine
prop1!: number;

@decorIdProp() // works fine
@decorateStr() // compile error (prop value type mismatch)
@decorateAny() // works fine
_id!: number;

@decorIdProp() // compile error (prop value type mismatch)
@decorateStr() // works fine
@decorateAny() // works fine
id!: string;
}
```
## Logical

### [`If`](#provided-type-definitions-and-runtime-units "Go back to contents")

Sequentially performs the following logic:

Expands to `TIfTrue` if `TCond extends true`.

Expands to `TElse` if `TCond extends false`.

Expands to `TIfCondIsBool` if `TCond extends boolean`.

*As a convention, enclose `TCond` argument in parens.*

```ts
type t0 = If<(true), number, string>; // number
type t1 = If<(false), number, string>; // string
type t2 = If<(boolean), number, string, bigint>; // bigint

type t3 = If<(And<[NotExtends<22, number>, true, true]>),
string,
If<(false), // nested condition
number,
string
>>; // string

// You may use leading ampersand or pipe in order to explicitly separate branches visually
type t4 = If<(true)
| number, // you may use & instead of |

| string
>; // number
```

### [`Not`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines `false` unit type if `T extends true`.
Defines `true` unit type if `T extends false`.
Defines `TIfTIsBool` when `T` is exactly `boolean` type.

```ts
type t0 = Not; // false
type t1 = Not; // true
type t2 = Not; // number
type t3 = Not>; // true
```
### [`And/Nand`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines `true` or `false` accroding to the definition of `and/nand(negated and)` logical operator.
It gets applied to all the argumets in the given tuple type `T`.

```ts
type t0 = And<[true, true, true]>; // true
type t1 = And; // true
type t2 = And<[true, false, true]> // false

type t3 = And; // false
type t4 = And<[boolean, true]>; // false

type t5 = Nand<[true, true]>; // false
```

### [`Or/Nor`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines `true` or `false` accroding to the definition of `or/nor(negated or)` logical operator.
It gets applied to all the argumets in the given tuple type `T`.

```ts
type t0 = Or<[false, false, false]>; // false
type t1 = Or; // false
type t2 = Or<[false, true, false]> // true

type t3 = Or; // true
type t4 = Or<[boolean, false]>; // true

type t5 = Nor<[true, true]>; // false
```

### [`[Not]Extends`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines `true` if `TExtender` is assignable to `TExtendee`, otherwise `false`.

It verifies that you may physically assign a value of type `TExtender` to `TExtendee`.
That's why union types with excess members that are not assignable to `TExtendee`
will evaluate to `false`.

```ts
type t0 = Extends; // false
type t1 = Extends; // true
type t2 = Extends; // true

type t3 = NotExtends<22, number>; // false
```

### [`AreSame`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines `true` if `T1` is exactly `T2`, `false` otherwise.
Even `AreSame` expands to `false`. Only the same types expand to `true`.

It doesn't tolerate co/bi/contravaraince, only the types of exactly the same shapes (excluding function types limitation) will cause to return `true`.

Beware that this type works as vanilla `extends` clause with function types,
so comparing functions is not that strict.

```ts
type t0 = AreSame<{}, { num: number }>; // false
type t1 = AreSame<
{ num: number, str: string },
{ num: number, str: string }
>; // true
type t2 = AreSame; // false
type t8 = AreSame; // true
type t9 = AreSame<[number], [number]>; // true
type t10 = AreSame<[number, string], [number]>; // false
```

### [`Is[Not]Any`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines `true[false]` if `TSuspect` is exactly of `any` type, `false[true]` otherwise.

```ts
type t0 = IsAny; // true
type t1 = IsAny; // false
type t2 = IsAny; // false
type t3 = IsAny; // false

type t4 = IsNotAny; // false
type t5 = IsNotAny; // true
// ...
```

### [`Is[Not]Unknown`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines `true[false]` if `TSuspect` is exactly of `unknown` type, `false[true]` otherwise.

```ts
type t0 = IsUnknown; // true
type t1 = IsUnknown; // false

type t2 = IsNotUnknown; // true
// ...
```

## Runtime

### [`reinterpret(value: any): T`](#provided-type-definitions-and-runtime-units "Go back to contents")

C++ style operator, a syntactic sugar for writing casts like
`value as any as T` when a simple `value as T` cast cannot be performed.
Use it with caution!

This function is actually noop at runtime, all it does is it suppresses
*'inability to cast'* *tsc* error. It's better to use this function rather than
`value as any as T` cast, because it amplifies your attention to such uneven
places in code and it may be easier to do a Ctrl + F search for these.

```ts
interface User {
// ...
}
type UserUpdate = DeepPartial>;

const userUpd: UserUpdate = // ...

Object.assign(userUpd, {
password: 'somepassword-pfff', otherRequiredFields: // ...
});

// For future devs: reinterpreting here, because userUpd has the same shape as `User`
let user = reinterpret(userUpd);

// `typeof user` is `User`
```

### [`class Debug.UnreachableCodeError`](#provided-type-definitions-and-runtime-units "Go back to contents")
Class used to perform `never` type value checks in unreachable code.

```ts
const val: string | number;

if (typeof val === 'string') {
return null;
} else if (typeof val === 'number') {
throw new Debug.UnreachableCodeError(val); // compiler error: val is not of type `never` here
return;
} else {
throw new Debug.UnreachableCodeError(val); // this is ok val has `never` type here
}

enum Enum {
A, B, C
}
let suspect: Enum = // ...
switch (suspect) {
case Enum.A: return;
case Enum.B: return;
default: {
// compiler error, this path is reachable
// as we didn't handle `suspect === Enum.C` case
throw new Debug.UnreachableCodeError(suspect);
}
}
```

## Misc

### [`Tag`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines nominal type by adding a property with `TTagName` value to `TTarget`.
`TTagName` must be unique across your application, treat it like the name of
your nominal type.

With this type, you may pick particular subclass of values from the given type and force
your clients to filter other values that are assignable to `TTarget` but don't
obey to your prerequisites, thus making them pay more attention to them.

```ts
type PositiveInt = Tag;
type CsvString = Tag;

// Prerequisites: `userId > 0`
async function getUser(userId: PositiveInt) {
return userRepository.findById(userId);
}

// Prerequisites: given string must be valid csv
function parseCsv(csvString: CsvString) {
// Here you may be sure that client payed attention to checking the input

const lines = csvString.split('\n').map(line => line.split(','));
}

getUser(-2); // compile error
getUser(58); // compile error
getUser(58 as PositiveInt); // fine (explicit cast pays your attention to prerequisites)

parseCsv('\nbla bla'); // compile error
parseCsv('a,b,c\nd,e,f' as CsvString); // fine
```

### [`UnionToIntersection`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines an intersection type of all union's items.

Because of TypeScript boolean representation as `type boolean = true | false`
you get the following result:
`UnionToIntersection` is `true & false`

```ts
// string & number & number[]
type t0 = UnionToIntersection;
```

### [`UnpackPromise`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines the type of value, which is passed to `TPromise.then(cb)` `cb` callback.

```ts
type t0 = UnpackPromise>; // number;
type t1 = UnpackPromise>; // void;

// Promise;
type t2 = UnpackPromise<
Promise>
>;

// string
type t3 = UnpackPromise>
>>;
```

### [`PickAsOptional/Required/Readonly/Mutable/NullableProps`](#provided-type-definitions-and-runtime-units "Go back to contents")

Shorthand for `Partial/Required/Readonly/Mutable/NullableProps>`, but better optimized (into one mapped object type).

```ts
interface User {
readonly id: number;
name?: string;
bio: string;
}
PickAsOptional === Partial>
PickAsRequired === Required>
PickAsReadonly === Readonly>

// ...
```

### [`[Deep]Nullable`](#provided-type-definitions-and-runtime-units "Go back to contents")
`Nullable` defines type `T` that may also be `null` or `undefined`:
```ts
export type Nullable = T | undefined | null;
```

`DeepNullable` defines the same type as `TObj` but with all properties made `NonNullable<>` recursively.

```ts
interface User {
id: number;
name: {
first: string;
last: string;
};
}

/*
Nullable<{
id?: Nullable;
name?: Nullable<{
first?: Nullable;
last?: Nullable;
}>;
}>
*/
type t0 = DeepNullable;
```

### [`Primitive`](#provided-type-definitions-and-runtime-units "Go back to contents")
Defines a union of all possible value types defined in the language,
`null` and `undefined` are considered to be primitive types.

```ts
export type Primitive = (
| number
| string
| boolean
| undefined
| symbol
| null
| bigint
);
```

### [`TypeName`](#provided-type-definitions-and-runtime-units "Go back to contents")

Defines a union of all possible strings retuned by applying `typeof` operator.

```ts
export type TypeName = (
| 'number'
| 'string'
| 'boolean'
| 'undefined'
| 'object'
| 'function'
| 'symbol'
| 'bigint'
);
```