utility-types
- Version 3.11.0
- Published
- 64.3 kB
- No dependencies
- MIT license
Install
npm i utility-types
yarn add utility-types
pnpm add utility-types
Overview
Utility Types Collection for TypeScript
Index
Functions
Type Aliases
- $Call
- $Diff
- $ElementType
- $Keys
- $NonMaybeType
- $PropertyType
- $ReadOnly
- $Shape
- $Values
- Assign
- Brand
- Class
- DeepNonNullable
- DeepPartial
- DeepReadonly
- DeepRequired
- Diff
- Falsey
- Falsy
- FunctionKeys
- Intersection
- Mutable
- MutableKeys
- NonFunctionKeys
- NonUndefined
- Nullish
- Omit
- OmitByValue
- OmitByValueExact
- Optional
- OptionalKeys
- Overwrite
- PickByValue
- PickByValueExact
- Primitive
- PromiseType
- ReadonlyKeys
- Required
- RequiredKeys
- SetComplement
- SetDifference
- SetIntersection
- Subtract
- SymmetricDifference
- Unionize
- UnionToIntersection
- ValuesType
- Writable
- WritableKeys
Functions
function getReturnOfExpression
getReturnOfExpression: <RT>(expression: (...params: any[]) => RT) => RT;
getReturnOfExpression
Parameter expression
: (...params: any[]) => RT
Returns
undefined as RT
Deprecated
from TS v2.8 use built-in ReturnType or $Call API infer the return type from a given "expression" (at runtime it's equivalent of "noop") RT - ReturnType
function isFalsy
isFalsy: (val: unknown) => val is Falsy;
Tests for Falsy by simply applying negation
!
to the testedval
.The value is mostly in added type-information and explicity, but in case of this simple type much the same can often be archived by just using negation
!
:Example 1
const consumer = (value: boolean | Falsy) => { if (!value) { return ; } type newType = typeof value; // === true // do stuff };
function isNullish
isNullish: (val: unknown) => val is null;
Tests for Nullish by simply comparing
val
for equality withnull
.Example 1
const consumer = (param: Nullish | string): string => { if (isNullish(param)) { // typeof param === Nullish return String(param) + ' was Nullish'; } // typeof param === string return param.toString(); };
function isPrimitive
isPrimitive: (val: unknown) => val is Primitive;
Tests for one of the [
Primitive
](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) types using the JavaScript [typeof
](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) operatorClarification: TypeScript overloads this operator to produce TypeScript types if used in context of types.
Parameter val
The value to be tested
Returns
If
val
is primitive. If used in the flow of the program typescript will infer type-information from this.Example 1
const consumer = (value: Primitive | Primitive[]) => { if (isPrimitive(value)) { return console.log('Primitive value: ', value); } // type of value now inferred as Primitive[] value.map((primitive) => consumer(primitive)); };
Type Aliases
type $Call
type $Call<Fn extends (...args: any[]) => any> = Fn extends (arg: any) => infer RT ? RT : never;
$Call Get the return type from a given typeof expression
Example 1
// Common use-case const add = (amount: number) => ({ type: 'ADD' as 'ADD', payload: amount }); type AddAction = $Call<typeof add>; // { type: 'ADD'; payload: number }
// Examples migrated from Flow docs type ExtractPropType<T extends { prop: any }> = (arg: T) => T['prop']; type Obj = { prop: number }; type PropType = $Call<ExtractPropType>; // number
type ExtractReturnType<T extends () => any> = (arg: T) => ReturnType; type Fn = () => number; type FnReturnType = $Call<ExtractReturnType>; // number
See Also
https://flow.org/en/docs/types/utilities/#toc-call
type $Diff
type $Diff<T extends U, U extends object> = Pick<T, SetComplement<keyof T, keyof U>>;
$Diff Get the set difference of a given object types
T
andU
(T \ U
)Example 1
type Props = { name: string; age: number; visible: boolean }; type DefaultProps = { age: number };
// Expect: { name: string; visible: boolean; } type RequiredProps = Diff<Props, DefaultProps>;
See Also
https://flow.org/en/docs/types/utilities/#toc-diff
type $ElementType
type $ElementType< T extends { [P in K & any]: any; }, K extends keyof T | number> = T[K];
$ElementType Get the type of elements inside of array, tuple or object of type
T
, that matches the given index typeK
Example 1
// Expect: string; type Props = { name: string; age: number; visible: boolean }; type NameType = $ElementType<Props, 'name'>;
// Expect: boolean type Tuple = [boolean, number]; type A = $ElementType<Tuple, '0'>; // Expect: number type B = $ElementType<Tuple, '1'>;
// Expect: boolean type Arr = boolean[]; type ItemsType = $ElementType<Arr, number>;
// Expect: number type Obj = { [key: string]: number }; type ValuesType = $ElementType<Obj, string>;
See Also
https://flow.org/en/docs/types/utilities/#toc-elementtype
type $Keys
type $Keys<T extends object> = keyof T;
$Keys Get the union type of all the keys in an object type
T
Example 1
type Props = { name: string; age: number; visible: boolean };
// Expect: "name" | "age" | "visible" type PropsKeys = $Keys;
See Also
https://flow.org/en/docs/types/utilities/#toc-keys
type $NonMaybeType
type $NonMaybeType<T> = NonNullable<T>;
$NonMaybeType Excludes null and undefined from T
Example 1
type MaybeName = string | null;
// Expect: string type Name = $NonMaybeType;
See Also
https://flow.org/en/docs/types/utilities/#toc-nonmaybe
type $PropertyType
type $PropertyType<T extends object, K extends keyof T> = T[K];
$PropertyType Get the type of property of an object at a given key
K
Example 1
// Expect: string; type Props = { name: string; age: number; visible: boolean }; type NameType = $PropertyType<Props, 'name'>;
// Expect: boolean type Tuple = [boolean, number]; type A = $PropertyType<Tuple, '0'>; // Expect: number type B = $PropertyType<Tuple, '1'>;
See Also
https://flow.org/en/docs/types/utilities/#toc-propertytype
type $ReadOnly
type $ReadOnly<T extends object> = DeepReadonly<T>;
$ReadOnly Get the read-only version of a given object type
T
(it works on nested data structure)Example 1
type Props = { name: string; age: number; visible: boolean };
// Expect: Readonly<{ name: string; age: number; visible: boolean; }> type ReadOnlyProps = $ReadOnly;
See Also
https://flow.org/en/docs/types/utilities/#toc-readonly
type $Shape
type $Shape<T extends object> = Partial<T>;
$Shape Copies the shape of the type supplied, but marks every field optional.
Example 1
type Props = { name: string; age: number; visible: boolean };
// Expect: Partial type PartialProps = $Shape;
See Also
https://flow.org/en/docs/types/utilities/#toc-shape
type $Values
type $Values<T extends object> = T[keyof T];
$Values Get the union type of all the values in an object type
T
Example 1
type Props = { name: string; age: number; visible: boolean };
// Expect: string | number | boolean type PropsValues = $Values;
See Also
https://flow.org/en/docs/types/utilities/#toc-values
type Assign
type Assign< T extends object, U extends object, I = Diff<T, U> & Intersection<U, T> & Diff<U, T>> = Pick<I, keyof I>;
Assign From
U
assign properties toT
(just like object assign)Example 1
type Props = { name: string; age: number; visible: boolean }; type NewProps = { age: string; other: string };
// Expect: { name: string; age: number; visible: boolean; other: string; } type ExtendedProps = Assign<Props, NewProps>;
type Brand
type Brand<T, U> = T & { __brand: U;};
Brand Define nominal type of U based on type of T. Similar to Opaque types in Flow.
Example 1
type USD = Brand<number, "USD"> type EUR = Brand<number, "EUR">
const tax = 5 as USD; const usd = 10 as USD; const eur = 10 as EUR;
function gross(net: USD): USD { return (net + tax) as USD; }
// Expect: No compile error gross(usd); // Expect: Compile error (Type '"EUR"' is not assignable to type '"USD"'.) gross(eur);
type Class
type Class<T> = new (...args: any[]) => T;
Class Represents constructor of type T
Example 1
class Store {} function makeStore(storeClass: Class): Store { return new storeClass(); }
See Also
https://flow.org/en/docs/types/utilities/#toc-class
type DeepNonNullable
type DeepNonNullable<T> = T extends (...args: any[]) => any ? T : T extends any[] ? _DeepNonNullableArray<T[number]> : T extends object ? _DeepNonNullableObject<T> : T;
DeepNonNullable NonNullable that works for deeply nested structure
Example 1
// Expect: { // first: { // second: { // name: string; // }; // }; // } type NestedProps = { first?: null | { second?: null | { name?: string | null | undefined; }; }; }; type RequiredNestedProps = DeepNonNullable;
type DeepPartial
type DeepPartial<T> = { [P in keyof T]?: _DeepPartial<T[P]>;};
DeepPartial Partial that works for deeply nested structure
Example 1
// Expect: { // first?: { // second?: { // name?: string; // }; // }; // } type NestedProps = { first: { second: { name: string; }; }; }; type PartialNestedProps = DeepPartial;
type DeepReadonly
type DeepReadonly<T> = T extends ((...args: any[]) => any) | Primitive ? T : T extends _DeepReadonlyArray<infer U> ? _DeepReadonlyArray<U> : T extends _DeepReadonlyObject<infer V> ? _DeepReadonlyObject<V> : T;
DeepReadonly Readonly that works for deeply nested structure
Example 1
// Expect: { // readonly first: { // readonly second: { // readonly name: string; // }; // }; // } type NestedProps = { first: { second: { name: string; }; }; }; type ReadonlyNestedProps = DeepReadonly;
type DeepRequired
type DeepRequired<T> = T extends (...args: any[]) => any ? T : T extends any[] ? _DeepRequiredArray<T[number]> : T extends object ? _DeepRequiredObject<T> : T;
DeepRequired Required that works for deeply nested structure
Example 1
// Expect: { // first: { // second: { // name: string; // }; // }; // } type NestedProps = { first?: { second?: { name?: string; }; }; }; type RequiredNestedProps = DeepRequired;
type Diff
type Diff<T extends object, U extends object> = Pick< T, SetDifference<keyof T, keyof U>>;
Diff From
T
remove properties that exist inU
Example 1
type Props = { name: string; age: number; visible: boolean }; type DefaultProps = { age: number };
// Expect: { name: string; visible: boolean; } type DiffProps = Diff<Props, DefaultProps>;
type Falsey
type Falsy = false | '' | 0 | null | undefined;
Falsy Type representing falsy values in TypeScript:
false | "" | 0 | null | undefined
Example 1
type Various = 'a' | 'b' | undefined | false;
// Expect: "a" | "b" Exclude<Various, Falsy>;
type Falsy
type Falsy = false | '' | 0 | null | undefined;
Falsy Type representing falsy values in TypeScript:
false | "" | 0 | null | undefined
Example 1
type Various = 'a' | 'b' | undefined | false;
// Expect: "a" | "b" Exclude<Various, Falsy>;
type FunctionKeys
type FunctionKeys<T extends object> = { [K in keyof T]-?: NonUndefined<T[K]> extends Function ? K : never;}[keyof T];
FunctionKeys Get union type of keys that are functions in object type
T
Example 1
type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;};
// Expect: "setName | someFn" type Keys = FunctionKeys;
type Intersection
type Intersection<T extends object, U extends object> = Pick< T, Extract<keyof T, keyof U> & Extract<keyof U, keyof T>>;
Intersection From
T
pick properties that exist inU
Example 1
type Props = { name: string; age: number; visible: boolean }; type DefaultProps = { age: number };
// Expect: { age: number; } type DuplicateProps = Intersection<Props, DefaultProps>;
type Mutable
type Mutable<T> = { -readonly [P in keyof T]: T[P];};
Mutable From
T
make all properties become mutableExample 1
type Props = { readonly name: string; readonly age: number; readonly visible: boolean; };
// Expect: { name: string; age: number; visible: boolean; } Mutable;
type MutableKeys
type MutableKeys<T extends object> = { [P in keyof T]-?: IfEquals< { [Q in P]: T[P]; }, { -readonly [Q in P]: T[P]; }, P >;}[keyof T];
MutableKeys Get union type of keys that are mutable in object type
T
Credit: Matt McCutchen https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescriptExample 1
type Props = { readonly foo: string; bar: number };
// Expect: "bar" type Keys = MutableKeys;
type NonFunctionKeys
type NonFunctionKeys<T extends object> = { [K in keyof T]-?: NonUndefined<T[K]> extends Function ? never : K;}[keyof T];
NonFunctionKeys Get union type of keys that are non-functions in object type
T
Example 1
type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;};
// Expect: "name | someKey" type Keys = NonFunctionKeys;
type NonUndefined
type NonUndefined<A> = A extends undefined ? never : A;
NonUndefined Exclude undefined from set
A
Example 1
// Expect: "string | null" SymmetricDifference<string | null | undefined>;
type Nullish
type Nullish = null | undefined;
Nullish Type representing [nullish values][https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing] in TypeScript:
null | undefined
Example 1
type Various = 'a' | 'b' | undefined;
// Expect: "a" | "b" Exclude<Various, Nullish>;
type Omit
type Omit<T, K extends keyof any> = Pick<T, SetDifference<keyof T, K>>;
Omit (complements Pick) From
T
remove a set of properties by keyK
Example 1
type Props = { name: string; age: number; visible: boolean };
// Expect: { name: string; visible: boolean; } type Props = Omit<Props, 'age'>;
type OmitByValue
type OmitByValue<T, ValueType> = Pick< T, { [Key in keyof T]-?: T[Key] extends ValueType ? never : Key; }[keyof T]>;
OmitByValue From
T
remove a set of properties by value matchingValueType
. Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c)Example 1
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { reqUndef: number | undefined; opt?: string; } type Props = OmitByValue<Props, number>; // Expect: { opt?: string; } type Props = OmitByValue<Props, number | undefined>;
type OmitByValueExact
type OmitByValueExact<T, ValueType> = Pick< T, { [Key in keyof T]-?: [ValueType] extends [T[Key]] ? [T[Key]] extends [ValueType] ? never : Key : Key; }[keyof T]>;
OmitByValueExact From
T
remove a set of properties by value matching exactValueType
.Example 1
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { reqUndef: number | undefined; opt?: string; } type Props = OmitByValueExact<Props, number>; // Expect: { req: number; opt?: string } type Props = OmitByValueExact<Props, number | undefined>;
type Optional
type Optional<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
Optional From
T
make a set of properties by keyK
become optionalExample 1
type Props = { name: string; age: number; visible: boolean; };
// Expect: { name?: string; age?: number; visible?: boolean; } type Props = Optional;
// Expect: { name: string; age?: number; visible?: boolean; } type Props = Optional<Props, 'age' | 'visible'>;
type OptionalKeys
type OptionalKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? K : never;}[keyof T];
OptionalKeys Get union type of keys that are optional in object type
T
Example 1
type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };
// Expect: "opt" | "optUndef" type Keys = OptionalKeys;
See Also
https://stackoverflow.com/questions/52984808/is-there-a-way-to-get-all-required-properties-of-a-typescript-object
type Overwrite
type Overwrite< T extends object, U extends object, I = Diff<T, U> & Intersection<U, T>> = Pick<I, keyof I>;
Overwrite From
U
overwrite properties toT
Example 1
type Props = { name: string; age: number; visible: boolean }; type NewProps = { age: string; other: string };
// Expect: { name: string; age: string; visible: boolean; } type ReplacedProps = Overwrite<Props, NewProps>;
type PickByValue
type PickByValue<T, ValueType> = Pick< T, { [Key in keyof T]-?: T[Key] extends ValueType ? Key : never; }[keyof T]>;
PickByValue From
T
pick a set of properties by value matchingValueType
. Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c)Example 1
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { req: number } type Props = PickByValue<Props, number>; // Expect: { req: number; reqUndef: number | undefined; } type Props = PickByValue<Props, number | undefined>;
type PickByValueExact
type PickByValueExact<T, ValueType> = Pick< T, { [Key in keyof T]-?: [ValueType] extends [T[Key]] ? [T[Key]] extends [ValueType] ? Key : never : never; }[keyof T]>;
PickByValueExact From
T
pick a set of properties by value matching exactValueType
.Example 1
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { req: number } type Props = PickByValueExact<Props, number>; // Expect: { reqUndef: number | undefined; } type Props = PickByValueExact<Props, number | undefined>;
type Primitive
type Primitive = string | number | bigint | boolean | symbol | null | undefined;
Primitive Type representing [
Primitive
](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) types in TypeScript:string | number | bigint | boolean | symbol | null | undefined
Example 1
type Various = number | string | object;
// Expect: object type Cleaned = Exclude<Various, Primitive>
type PromiseType
type PromiseType<T extends Promise<any>> = T extends Promise<infer U> ? U : never;
PromiseType Obtain Promise resolve type
Example 1
// Expect: string; type Response = PromiseType<Promise>;
type ReadonlyKeys
type ReadonlyKeys<T extends object> = { [P in keyof T]-?: IfEquals< { [Q in P]: T[P]; }, { -readonly [Q in P]: T[P]; }, never, P >;}[keyof T];
ReadonlyKeys Get union type of keys that are readonly in object type
T
Credit: Matt McCutchen https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescriptExample 1
type Props = { readonly foo: string; bar: number };
// Expect: "foo" type Keys = ReadonlyKeys;
type Required
type AugmentedRequired<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Required<Pick<T, K>>;
Required From
T
make a set of properties by keyK
become requiredExample 1
type Props = { name?: string; age?: number; visible?: boolean; };
// Expect: { name: string; age: number; visible: boolean; } type Props = Required;
// Expect: { name?: string; age: number; visible: boolean; } type Props = Required<Props, 'age' | 'visible'>;
type RequiredKeys
type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K;}[keyof T];
RequiredKeys Get union type of keys that are required in object type
T
Example 1
type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };
// Expect: "req" | "reqUndef" type Keys = RequiredKeys;
See Also
https://stackoverflow.com/questions/52984808/is-there-a-way-to-get-all-required-properties-of-a-typescript-object
type SetComplement
type SetComplement<A, A1 extends A> = SetDifference<A, A1>;
SetComplement Set complement of given union types
A
and (it's subset)A1
Example 1
// Expect: "1" SetComplement<'1' | '2' | '3', '2' | '3'>;
type SetDifference
type SetDifference<A, B> = A extends B ? never : A;
SetDifference (same as Exclude) Set difference of given union types
A
andB
Example 1
// Expect: "1" SetDifference<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: string | number SetDifference<string | number | (() => void), Function>;
type SetIntersection
type SetIntersection<A, B> = A extends B ? A : never;
SetIntersection (same as Extract) Set intersection of given union types
A
andB
Example 1
// Expect: "2" | "3" SetIntersection<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: () => void SetIntersection<string | number | (() => void), Function>;
type Subtract
type Subtract<T extends T1, T1 extends object> = Pick< T, SetComplement<keyof T, keyof T1>>;
Subtract From
T
remove properties that exist inT1
(T1
has a subset of the properties ofT
)Example 1
type Props = { name: string; age: number; visible: boolean }; type DefaultProps = { age: number };
// Expect: { name: string; visible: boolean; } type RestProps = Subtract<Props, DefaultProps>;
type SymmetricDifference
type SymmetricDifference<A, B> = SetDifference<A | B, A & B>;
SymmetricDifference Set difference of union and intersection of given union types
A
andB
Example 1
// Expect: "1" | "4" SymmetricDifference<'1' | '2' | '3', '2' | '3' | '4'>;
type Unionize
type Unionize<T extends object> = { [P in keyof T]: { [Q in P]: T[P]; };}[keyof T];
Unionize Disjoin object to form union of objects, each with single property
Example 1
type Props = { name: string; age: number; visible: boolean };
// Expect: { name: string; } | { age: number; } | { visible: boolean; } type UnionizedType = Unionize;
type UnionToIntersection
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( k: infer I) => void ? I : never;
UnionToIntersection Get intersection type given union type
U
Credit: jcalzExample 1
// Expect: { name: string } & { age: number } & { visible: boolean } UnionToIntersection<{ name: string } | { age: number } | { visible: boolean }>
See Also
https://stackoverflow.com/a/50375286/7381355
type ValuesType
type ValuesType<T extends ReadonlyArray<any> | ArrayLike<any> | Record<any, any>> = T extends ReadonlyArray<any> ? T[number] : T extends ArrayLike<any> ? T[number] : T extends object ? T[keyof T] : never;
ValuesType Get the union type of all the values in an object, array or array-like type
T
Example 1
type Props = { name: string; age: number; visible: boolean }; // Expect: string | number | boolean type PropsValues = ValuesType;
type NumberArray = number[]; // Expect: number type NumberItems = ValuesType;
type ReadonlySymbolArray = readonly symbol[]; // Expect: symbol type SymbolItems = ValuesType;
type NumberTuple = [1, 2]; // Expect: 1 | 2 type NumberUnion = ValuesType;
type ReadonlyNumberTuple = readonly [1, 2]; // Expect: 1 | 2 type AnotherNumberUnion = ValuesType;
type BinaryArray = Uint8Array; // Expect: number type BinaryItems = ValuesType;
type Writable
type Writable<T> = Mutable<T>;
type WritableKeys
type WritableKeys<T extends object> = MutableKeys<T>;
Package Files (5)
Dependencies (0)
No dependencies.
Dev Dependencies (8)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/utility-types
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/utility-types)
- HTML<a href="https://www.jsdocs.io/package/utility-types"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4309 ms. - Missing or incorrect documentation? Open an issue for this package.