ts-essentials
All essential TypeScript types in one place 🤙
Install
npm install --save-dev ts-essentials
👉 We require typescript>=4.5
. If you're looking for support for older TS versions, please have a look at the
TypeScript dependency table
👉 As we really want types to be stricter, we require enabled strictNullChecks in your project
API
ts-essentials
is a set of high-quality, useful TypeScript types that make writing type-safe code easier.
Basic
Builtin
- Matches primitive, function, date, error or regular expressionKeyofBase
-keyofStringsOnly
-tolerant analogue forPropertyKey
Prettify<Type>
- flattens type and makes it more readable on the hover in your IDEPrimitive
- Matches any primitive valueStrictExclude<UnionType, ExcludedMembers>
- Constructs a type by excluding fromUnionType
all union members that are assignable toExcludedMembers
. This is stricter version ofExclude
StrictExtract<Type, Union>
- Constructs a type by extracting fromType
all union members that are assignable toUnion
. This is stricter version ofExtract
StrictOmit<Type, Keys>
- Constructs a type by picking all properties fromType
and then removingKeys
. This is stricter version ofOmit
Writable<Type>
- Constructs a type with removedreadonly
for all properties ofType
, meaning the properties of the constructed type can be reassigned
Utility types
AsyncOrSync<Type>
- Constructs a type withType
orPromiseLike<Type>
AsyncOrSyncType<Type>
- UnwrapsAsyncOrSync
typeDictionary<Type, Keys?>
- Constructs a required object type which property keys areKeys
(string
by default) and which property values areType
Merge<Object1, Object2>
- Constructs a type by picking all properties fromObject1
andObject2
. Property values fromObject2
override property values fromObject1
when property keys are the sameMergeN<Tuple>
- Constructs a type by merging objects with typeMerge
in tupleTuple
recursivelyNewable<ReturnType>
- Constructs a class type with constructor which has return typeReturnType
NonNever<Type>
- Constructs a type by picking all properties from typeType
which values don't equal tonever
OmitProperties<Type, Value>
- Constructs a type by picking all properties from typeType
and removing those properties which values equal toValue
Opaque<Type, Token>
- Constructs a type which is a subset ofType
with a specified unique tokenToken
PathValue<Type, Path>
- Constructs a path value for typeType
and pathPath
Paths<Type>
- Constructs a union type by picking all possible paths for typeType
PickProperties<Type, Value>
- Constructs a type by picking all properties from typeType
which values equal toValue
SafeDictionary<Type, Keys?>
- Constructs an optional object type which property keys areKeys
(string
by default) and which property values areType
UnionToIntersection<Union>
- Constructs a intersection type from union typeUnion
ValueOf<Type>
- Constructs a type for typeType
and equals to a primitive for primitives, array elements for arrays, function return type for functions or object property values for objectsXOR<Type1, Type2, Type3?, ..., Type50?>
- Construct a type which is assignable to either typeType1
,Type2
but not both. Starting in ts-essentials@10, it supports up to 50 generic types.
Mark wrapper types
MarkOptional<Type, Keys>
- Constructs a type by picking all properties from typeType
where propertiesKeys
are set as optional, meaning they aren't requiredMarkReadonly<Type, Keys>
- Constructs a type by picking all properties from typeType
where propertiesKeys
are set toreadonly
, meaning they cannot be reassignedMarkRequired<Type, Keys>
- Constructs a type by picking all properties from typeType
where propertiesKeys
are set as requiredMarkWritable<Type, Keys>
- Constructs a type by picking all properties from typeType
where propertiesKeys
removereadonly
modifier, meaning they can be reassigned
Deep wrapper types
Buildable<Type>
- Constructs a type by combiningDeepPartial
andDeepWritable
, meaning all properties from typeType
are recursively set as non-readonly
and optional, meaning they can be reassigned and aren't requiredDeepNonNullable<Type>
- Constructs a type by picking all properties from typeType
recursively and excludenull
andundefined
property values from all of them. To make properties non-nullable on one level, useNonNullable<Type>
DeepNullable<Type>
- Constructs a type by picking all properties from typeType
recursively and includenull
property values for all of themDeepOmit<Type, Filter>
- Constructs a type by picking all properties from typeType
and removing properties which values arenever
ortrue
in typeFilter
. If you'd like typeFilter
to be validated against a structure ofType
, please useStrictDeepOmit<Type, Filter>
.DeepPartial<Type>
- Constructs a type by picking all properties from typeType
recursively and setting them as optional, meaning they aren't required. To make properties optional on one level, usePartial<Type>
DeepPick<Type, Filter>
- Constructs a type by picking set of properties, which have property valuesnever
ortrue
in typeFilter
, from typeType
. If you'd like typeFilter
to be validated against a structure ofType
, please useStrictDeepPick<Type, Filter>
.DeepReadonly<Type>
- Constructs a type by picking all properties from typeType
recursively and settingreadonly
modifier, meaning they cannot be reassigned. To make propertiesreadonly
on one level, useReadonly<Type>
DeepRequired<Type>
- Constructs a type by picking all properties from typeType
recursively and setting as required. To make properties required on one level, useRequired<Type>
DeepUndefinable<Type>
- Constructs a type by picking all properties from typeType
recursively and includeundefined
property values for all of themDeepWritable<Type>
- Constructs a type by picking all properties from typeType
recursively and removingreadonly
modifier, meaning they can be reassigned. To make properties writable on one level, useWritable<Type>
StrictDeepOmit<Type, Filter>
- Constructs a type by picking all properties from typeType
and removing properties which values arenever
ortrue
in typeFilter
. The typeFilter
is validated against a structure ofType
.StrictDeepPick<Type, Filter>
- Constructs a type by picking set of properties, which have property valuesnever
ortrue
in typeFilter
, from typeType
. The typeFilter
is validated against a structure ofType
.
Key types
OptionalKeys<Type>
- Constructs a union type by picking all optional properties of object typeType
PickKeys<Type, Value>
- Constructs a union type by picking all properties of object typeType
which values are assignable to typeValue
ReadonlyKeys<Type>
- Constructs a union type by picking allreadonly
properties of object typeType
, meaning their values cannot be reassignedRequiredKeys<Type>
- Constructs a union type by picking all required properties of object typeType
WritableKeys<Type>
- Constructs a union type by picking all writable properties of object typeType
, meaning their values can be reassigned
Type checkers
Exact<Type, Shape>
- ReturnsType
when typeType
andShape
are identical. Otherwise returnsnever
IsAny<Type>
- Returnstrue
when typeType
isany
. Otherwise returnsfalse
IsNever<Type>
- Returnstrue
when typeType
isnever
. Otherwise returnsfalse
IsUnknown<Type>
- Returnstrue
when typeType
isunknown
. Otherwise returnsfalse
IsTuple<Type>
- ReturnsType
when typeType
is tuple. Otherwise returnsnever
NonEmptyObject<Object>
- ReturnsObject
whenObject
has at least one key. Otherwise returnsnever
Arrays and Tuples
AnyArray<Type?>
- MatchesArray
orReadonlyArray
(Type
isany
by default)ArrayOrSingle<Type>
- MatchesType
orType[]
ElementOf<Type>
- Constructs a type which equals to array element type for typeType
Head<Type>
- Constructs a type which equals to first element in typeType
NonEmptyArray<Type>
- Matches array with at least one element of typeType
ReadonlyArrayOrSingle
- MatchesType
orreadonly Type[]
Tail<Type>
- Constructs a type which equals to elements but first one in typeType
Tuple<Type?>
- Matches type constraint for tuple with elements of typeType
(any
by default)
Change case
CamelCase<Type>
- Converts typeType
to camel case (e.g.camelCase
)DeepCamelCaseProperties<Type>
- Constructs a type by picking all properties from typeType
recursively and converting all of them to camel case
Function types
AnyFunction<Args?, ReturnType?>
- Matches function type with arguments typeArgs
(any[]
by default) and return typeReturnType
(any
by default)PredicateFunction
- Matches type constraint for type guard, meaning first argument is used in return type and return type is type predicatePredicateType<Type>
- Constructs a type which equals to narrowed type in predicate functionType
Utility functions
ts-essentials
to your dependencies
(npm install --save ts-essentials
) to avoid runtime errors
new UnreachableCaseError(value)
- Matches runtime class instance type that helps check exhaustiveness forvalue
. Whenvalue
isn'tnever
, it shows TypeScript errorassert(condition, message?)
- Matches runtime function that helps assertcondition
. Whencondition
is falsy, it throws an error withAssertion Error: ${message}
(message is"no additional info provided"
by default)createFactoryWithConstraint<Constraint>()(value)
- Matches runtime function, which validates that type ofvalue
matchesConstraint
without changing resulting type ofvalue
. Ponyfill forsatisfies
operatorisExact<Expected>()(actual)
- Matches runtime function, which validates that type ofactual
equals toExpected
. Otherwise shows TypeScript errornoop(..._args)
- Matches runtime function that does nothing with arguments_args
Search
When one of utility types is known by a different name, kindly ask adding it here for the better search.
ArrayValues
-ValueOf<Type>
Branded
-Opaque<Type, Token>
ConditionalKeys
-PickKeys<Type, Value>
Except
-StrictOmit<Type, Keys>
Get
-PathValue<Type, Path>
Mutable
-Writable<Type>
Nominal
-Opaque<Type, Token>
Set*
, e.g.SetOptional
-Mark*
, e.g.MarkReadonly<Type, Keys>
Unwrap
-Prettify<Type>
ValueOf
-DictionaryValues
Built-in types
TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.
Awaited<Type>
- This type is meant to model operations likeawait
inasync
functions, or the.then()
method onPromise
s - specifically, the way that they recursively unwrapPromise
sCapitalize<StringType>
- Converts the first character in the string to an uppercase equivalentConstructParameters<Type>
- Constructs a tuple or array type from the types of a constructor function typeType
Exclude<UnionType, ExcludedMembers>
- Constructs a type by excluding fromUnionType
all union members that are assignable toExcludedMembers
Extract<Type, Union>
- Constructs a type by extracting fromType
all union members that are assignable toUnion
InstanceType<Type>
- Constructs a type consisting of the instance type of a constructor function inType
Lowercase<StringType>
- Converts each character in the string to the lowercase equivalentNonNullable<Type>
- Constructs a type by excluding null and undefined fromType
Omit<Type, Keys>
- Constructs a type by picking all properties fromType
and then removingKeys
Parameters<Type>
- Constructs a tuple type from the types used in the parameters of a function typeType
Partial<Type>
- Constructs a type with all properties ofType
set to optionalPick<Type, Keys>
- Constructs a type by picking the set of propertiesKeys
fromType
Readonly<Type>
- Constructs a type with all properties ofType
set toreadonly
, meaning the properties of the constructed type cannot be reassignedRecord<Keys, Type>
- Constructs an object type whose property keys areKeys
and whose property values areType
Required<Type>
- Constructs a type consisting of all properties ofType
set to requiredReturnType<Type>
- Constructs a type consisting of the return type of function typeType
parameterUncapitalize<StringType>
- Converts the first character in the string to a lowercase equivalentUppercase<StringType>
- Converts each character in the string to the uppercase version
TypeScript dependency table
ts-essentials |
typescript / type of dependency |
---|---|
^10.0.0 |
^4.5.0 / peer optional |
^9.4.0 |
^4.1.0 / peer optional |
^8.0.0 |
^4.1.0 / peer |
^5.0.0 |
^3.7.0 / peer |
^3.0.1 |
^3.5.0 / peer |
^1.0.1 |
^3.2.2 / dev |
^1.0.0 |
^3.0.3 / dev |
Contributors
Special shout-out to active contributors:
- Kris Kaczor / 💻
- Xiao Liang / 💻
- Mateusz Burzyński / 💻
- Artur Kozak / 💻
- Zihua Wu / 💻
- Alexey Berezin / 💻
- Som Shekhar Mukherjee / 💻
And thanks goes to these wonderful people:
- Maciej Bembenista / 💻
- Michael Tontchev / 💻
- Thomas den Hollander / 💻
- Esa-Matti Suuronen
- Ilya Semenov / 💻
- Patricio Palladino
- Kevin Peno / 💻
- Dom Parfitt
- Eduardo Rafael / 💻
- Andrew C. Dvorak / 💻
- Adam Russell / 💻
- Piotr Szlachciak / 💻
- Mikhail Swift / 💻
- Ryan Zhang
- Francesco Borzì / 💻
- Marnick L'Eau
- Egor Gorbachev
- Bill Barry / 💻
- Andrzej Wódkiewicz / 💻
- Christian Junker
- Matthew Leffler / 💻
- studds / 💻
- Robert Vitonsky
- Itay Ronen / 💻
- Yaroslav Larin
- liaoyinglong / 💻
- Yannick Stachelscheid / 💻
- Peter Smolinský / 💻
- Anurag Hazra / 💻
- Bishwajit Jha / 💻
- Sergey Ukustov / 💻
- Homa Wong / 💻
- polyipseity / 💻
- Kristóf Poduszló / 💻
- MT Lewis / 💻
- Daniel Bertocci / 💻
- Myles J / 💻
💻 - contributions, i.e. links to commits by the user on this project
Contributions of any kind welcome! Read more