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 expressionJsonArray- Matches any JSON arrayJsonObject- Matches any JSON objectJsonPrimitive- Matches any JSON primitive valueJsonValue- Matches any JSON valueKeyofBase-keyofStringsOnly-tolerant analogue forPropertyKeyPrettify<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 fromUnionTypeall union members that are assignable toExcludedMembers. This is stricter version ofExcludeStrictExtract<Type, Union>- Constructs a type by extracting fromTypeall union members that are assignable toUnion. This is stricter version ofExtractStrictOmit<Type, Keys>- Constructs a type by picking all properties fromTypeand then removingKeys. This is stricter version ofOmitWritable<Type>- Constructs a type with removedreadonlyfor all properties ofType, meaning the properties of the constructed type can be reassigned
Utility types
AsyncOrSync<Type>- Constructs a type withTypeorPromiseLike<Type>AsyncOrSyncType<Type>- UnwrapsAsyncOrSynctypeDictionary<Type, Keys?>- Constructs a required object type which property keys areKeys(stringby default) and which property values areTypeMerge<Object1, Object2>- Constructs a type by picking all properties fromObject1andObject2. Property values fromObject2override property values fromObject1when property keys are the sameMergeN<Tuple>- Constructs a type by merging objects with typeMergein tupleTuplerecursivelyNewable<ReturnType>- Constructs a class type with constructor which has return typeReturnTypeOmitNeverProperties<Type>- Constructs a type by picking all properties from typeType, which values don't equal toneverOmitProperties<Type, Value>- Constructs a type by picking all properties from typeTypeand removing those properties which values equal toValueOpaque<Type, Token>- Constructs a type which is a subset ofTypewith a specified unique tokenTokenPathValue<Type, Path>- Constructs a path value for typeTypeand pathPathPaths<Type>- Constructs a union type by picking all possible paths for typeTypePickProperties<Type, Value>- Constructs a type by picking all properties from typeTypewhich values equal toValueRequireAtLeastOne<Type, Keys?>- Constructs a type with at least one required key fromKeys(keyof Typeby default) and other keys fromTypewhich are not part ofKeysRequireAtMostOne<Type, Keys?>- Constructs a type with at most one required key fromKeys(keyof Typeby default) and other keys fromTypewhich are not part ofKeysSafeDictionary<Type, Keys?>- Constructs an optional object type which property keys areKeys(stringby default) and which property values areTypeUnionToIntersection<Union>- Constructs a intersection type from union typeUnionValueOf<Type>- Constructs a type for typeTypeand 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,Type2but 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 typeTypewhere propertiesKeysare set as optional, meaning they aren't requiredMarkReadonly<Type, Keys>- Constructs a type by picking all properties from typeTypewhere propertiesKeysare set toreadonly, meaning they cannot be reassignedMarkRequired<Type, Keys>- Constructs a type by picking all properties from typeTypewhere propertiesKeysare set as requiredMarkWritable<Type, Keys>- Constructs a type by picking all properties from typeTypewhere propertiesKeysremovereadonlymodifier, meaning they can be reassigned
Deep wrapper types
Buildable<Type>- Constructs a type by combiningDeepPartialandDeepWritable, meaning all properties from typeTypeare recursively set as non-readonlyand optional, meaning they can be reassigned and aren't requiredDeepMarkOptional<Type, KeyPathUnion>- Constructs a type by picking all properties from typeTypewhere properties by pathsKeyPathUnionare set as optional. To mark properties optional on one level, useMarkOptional<Type, Keys>.DeepMarkRequired<Type, KeyPathUnion>- Constructs a type by picking all properties from typeTypewhere properties by pathsKeyPathUnionare set as required. To mark properties required on one level, useMarkRequired<Type, Keys>.DeepNonNullable<Type>- Constructs a type by picking all properties from typeTyperecursively and excludenullandundefinedproperty 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 typeTyperecursively and includenullproperty values for all of themDeepOmit<Type, Filter>- Constructs a type by picking all properties from typeTypeand removing properties which values areneverortruein typeFilter. If you'd like typeFilterto be validated against a structure ofType, please useStrictDeepOmit<Type, Filter>.DeepPartial<Type>- Constructs a type by picking all properties from typeTyperecursively 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 valuesneverortruein typeFilter, from typeType. If you'd like typeFilterto be validated against a structure ofType, please useStrictDeepPick<Type, Filter>.DeepReadonly<Type>- Constructs a type by picking all properties from typeTyperecursively and settingreadonlymodifier, meaning they cannot be reassigned. To make propertiesreadonlyon one level, useReadonly<Type>DeepRequired<Type>- Constructs a type by picking all properties from typeTyperecursively and setting as required. To make properties required on one level, useRequired<Type>DeepUndefinable<Type>- Constructs a type by picking all properties from typeTyperecursively and includeundefinedproperty values for all of themDeepWritable<Type>- Constructs a type by picking all properties from typeTyperecursively and removingreadonlymodifier, 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 typeTypeand removing properties which values areneverortruein typeFilter. The typeFilteris validated against a structure ofType.StrictDeepPick<Type, Filter>- Constructs a type by picking set of properties, which have property valuesneverortruein typeFilter, from typeType. The typeFilteris validated against a structure ofType.
Key types
OptionalKeys<Type>- Constructs a union type by picking all optional properties of object typeTypePickKeys<Type, Value>- Constructs a union type by picking all properties of object typeTypewhich values are assignable to typeValueReadonlyKeys<Type>- Constructs a union type by picking allreadonlyproperties of object typeType, meaning their values cannot be reassignedRequiredKeys<Type>- Constructs a union type by picking all required properties of object typeTypeUnionKeys<UnionType>- Constructs a union type by picking all properties from all union members ofUnionTypeWritableKeys<Type>- Constructs a union type by picking all writable properties of object typeType, meaning their values can be reassigned
Type checkers
IsAny<Type>- Returnstruewhen typeTypeisany. Otherwise returnsfalseIsExact<Type, Shape>- ReturnsTypewhen typeTypeandShapeare identical. Otherwise returnsneverIsNever<Type>- Returnstruewhen typeTypeisnever. Otherwise returnsfalseIsUnknown<Type>- Returnstruewhen typeTypeisunknown. Otherwise returnsfalseIsTuple<Type>- ReturnsTypewhen typeTypeis tuple. Otherwise returnsneverNonEmptyObject<Object>- ReturnsObjectwhenObjecthas at least one key. Otherwise returnsneverNonUnion<Type>- ReturnsTypewhenTypeis not an union. Otherwise returnsnever
Arrays and Tuples
AnyArray<Type?>- MatchesArrayorReadonlyArray(Typeisanyby default)AnyNonEmptyArray<Type>- Matches array with at least one element of typeTypeArrayOrSingle<Type>- MatchesTypeorType[]ElementOf<Type>- Constructs a type which equals to array element type for typeTypeHead<Type>- Constructs a type which equals to first element in typeTypeReadonlyArrayOrSingle- MatchesTypeorreadonly Type[]Tail<Type>- Constructs a type which equals to elements but first one in typeTypeTuple<Type?>- Matches type constraint for tuple with elements of typeType(anyby default)
Change case
CamelCase<Type>- Converts typeTypeto camel case (e.g.camelCase)DeepCamelCaseProperties<Type>- Constructs a type by picking all properties from typeTyperecursively 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(anyby 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. Whenvalueisn'tnever, it shows TypeScript errorassert(condition, message?)- Matches runtime function that helps assertcondition. Whenconditionis 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 ofvaluematchesConstraintwithout changing resulting type ofvalue. Ponyfill forsatisfiesoperatorisExact<Expected>()(actual)- Matches runtime function, which validates that type ofactualequals 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 likeawaitinasyncfunctions, or the.then()method onPromises - specifically, the way that they recursively unwrapPromisesCapitalize<StringType>- Converts the first character in the string to an uppercase equivalentConstructorParameters<Type>- Constructs a tuple or array type from the types of a constructor function typeTypeExclude<UnionType, ExcludedMembers>- Constructs a type by excluding fromUnionTypeall union members that are assignable toExcludedMembersExtract<Type, Union>- Constructs a type by extracting fromTypeall union members that are assignable toUnionInstanceType<Type>- Constructs a type consisting of the instance type of a constructor function inTypeLowercase<StringType>- Converts each character in the string to the lowercase equivalentNonNullable<Type>- Constructs a type by excluding null and undefined fromTypeNoInfer<Type>- Blocks inferences to the contained type. Other than blocking inferences,NoInfer<Type>is identical toTypeOmit<Type, Keys>- Constructs a type by picking all properties fromTypeand then removingKeysOmitThisParameter<Type>- Removes thethisparameter fromType. IfTypehas no explicitly declared this parameter, the result is simplyType. Otherwise, a new function type with no this parameter is created fromType. Generics are erased and only the last overload signature is propagated into the new function type.Parameters<Type>- Constructs a tuple type from the types used in the parameters of a function typeTypePartial<Type>- Constructs a type with all properties ofTypeset to optionalPick<Type, Keys>- Constructs a type by picking the set of propertiesKeysfromTypeReadonly<Type>- Constructs a type with all properties ofTypeset toreadonly, meaning the properties of the constructed type cannot be reassignedRecord<Keys, Type>- Constructs an object type whose property keys areKeysand whose property values areTypeRequired<Type>- Constructs a type consisting of all properties ofTypeset to requiredReturnType<Type>- Constructs a type consisting of the return type of function typeTypeparameterThisParameterType<Type>- Extracts the type of thethisparameter for a function type, orunknownif the function type has nothisparameterThisType<Type>- This utility does not return a transformed type. Instead, it serves as a marker for a contextualthistype. Note that thenoImplicitThisflag must be enabled to use this utilityUncapitalize<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 |
Limitations
- This project doesn't use
extendsConstraints oninferType Variables as it's introduced in TypeScript 4.7, but currently ts-essentials supports versions below, e.g. TypeScript 4.5. Read more in https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#extends-constraints-on-infer-type-variables
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
