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 expression
- JsonArray- Matches any JSON array
- JsonObject- Matches any JSON object
- JsonPrimitive- Matches any JSON primitive value
- JsonValue- Matches any JSON value
- KeyofBase-- keyofStringsOnly-tolerant analogue for- PropertyKey
- Prettify<Type>- flattens type and makes it more readable on the hover in your IDE
- Primitive- Matches any primitive value
- StrictExclude<UnionType, ExcludedMembers>- Constructs a type by excluding from- UnionTypeall union members that are assignable to- ExcludedMembers. This is stricter version of- Exclude
- StrictExtract<Type, Union>- Constructs a type by extracting from- Typeall union members that are assignable to- Union. This is stricter version of- Extract
- StrictOmit<Type, Keys>- Constructs a type by picking all properties from- Typeand then removing- Keys. This is stricter version of- Omit
- Writable<Type>- Constructs a type with removed- readonlyfor all properties of- Type, meaning the properties of the constructed type can be reassigned
Utility types
- AsyncOrSync<Type>- Constructs a type with- Typeor- PromiseLike<Type>
- AsyncOrSyncType<Type>- Unwraps- AsyncOrSynctype
- Dictionary<Type, Keys?>- Constructs a required object type which property keys are- Keys(- stringby default) and which property values are- Type
- Merge<Object1, Object2>- Constructs a type by picking all properties from- Object1and- Object2. Property values from- Object2override property values from- Object1when property keys are the same
- MergeN<Tuple>- Constructs a type by merging objects with type- Mergein tuple- Tuplerecursively
- Newable<ReturnType>- Constructs a class type with constructor which has return type- ReturnType
- OmitNeverProperties<Type>- Constructs a type by picking all properties from type- Type, which values don't equal to- never
- OmitProperties<Type, Value>- Constructs a type by picking all properties from type- Typeand removing those properties which values equal to- Value
- Opaque<Type, Token>- Constructs a type which is a subset of- Typewith a specified unique token- Token
- PathValue<Type, Path>- Constructs a path value for type- Typeand path- Path
- Paths<Type>- Constructs a union type by picking all possible paths for type- Type
- PickProperties<Type, Value>- Constructs a type by picking all properties from type- Typewhich values equal to- Value
- RequireAtLeastOne<Type, Keys?>- Constructs a type with at least one required key from- Keys(- keyof Typeby default) and other keys from- Typewhich are not part of- Keys
- RequireAtMostOne<Type, Keys?>- Constructs a type with at most one required key from- Keys(- keyof Typeby default) and other keys from- Typewhich are not part of- Keys
- SafeDictionary<Type, Keys?>- Constructs an optional object type which property keys are- Keys(- stringby default) and which property values are- Type
- UnionToIntersection<Union>- Constructs a intersection type from union type- Union
- ValueOf<Type>- Constructs a type for type- Typeand equals to a primitive for primitives, array elements for arrays, function return type for functions or object property values for objects
- XOR<Type1, Type2, Type3?, ..., Type50?>- Construct a type which is assignable to either type- Type1,- 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 type- Typewhere properties- Keysare set as optional, meaning they aren't required
- MarkReadonly<Type, Keys>- Constructs a type by picking all properties from type- Typewhere properties- Keysare set to- readonly, meaning they cannot be reassigned
- MarkRequired<Type, Keys>- Constructs a type by picking all properties from type- Typewhere properties- Keysare set as required
- MarkWritable<Type, Keys>- Constructs a type by picking all properties from type- Typewhere properties- Keysremove- readonlymodifier, meaning they can be reassigned
Deep wrapper types
- Buildable<Type>- Constructs a type by combining- DeepPartialand- DeepWritable, meaning all properties from type- Typeare recursively set as non-- readonlyand optional, meaning they can be reassigned and aren't required
- DeepMarkOptional<Type, KeyPathUnion>- Constructs a type by picking all properties from type- Typewhere properties by paths- KeyPathUnionare set as optional. To mark properties optional on one level, use- MarkOptional<Type, Keys>.
- DeepMarkRequired<Type, KeyPathUnion>- Constructs a type by picking all properties from type- Typewhere properties by paths- KeyPathUnionare set as required. To mark properties required on one level, use- MarkRequired<Type, Keys>.
- DeepNonNullable<Type>- Constructs a type by picking all properties from type- Typerecursively and exclude- nulland- undefinedproperty values from all of them. To make properties non-nullable on one level, use- NonNullable<Type>
- DeepNullable<Type>- Constructs a type by picking all properties from type- Typerecursively and include- nullproperty values for all of them
- DeepOmit<Type, Filter>- Constructs a type by picking all properties from type- Typeand removing properties which values are- neveror- truein type- Filter. If you'd like type- Filterto be validated against a structure of- Type, please use- StrictDeepOmit<Type, Filter>.
- DeepPartial<Type>- Constructs a type by picking all properties from type- Typerecursively and setting them as optional, meaning they aren't required. To make properties optional on one level, use- Partial<Type>
- DeepPick<Type, Filter>- Constructs a type by picking set of properties, which have property values- neveror- truein type- Filter, from type- Type. If you'd like type- Filterto be validated against a structure of- Type, please use- StrictDeepPick<Type, Filter>.
- DeepReadonly<Type>- Constructs a type by picking all properties from type- Typerecursively and setting- readonlymodifier, meaning they cannot be reassigned. To make properties- readonlyon one level, use- Readonly<Type>
- DeepRequired<Type>- Constructs a type by picking all properties from type- Typerecursively and setting as required. To make properties required on one level, use- Required<Type>
- DeepUndefinable<Type>- Constructs a type by picking all properties from type- Typerecursively and include- undefinedproperty values for all of them
- DeepWritable<Type>- Constructs a type by picking all properties from type- Typerecursively and removing- readonlymodifier, meaning they can be reassigned. To make properties writable on one level, use- Writable<Type>
- StrictDeepOmit<Type, Filter>- Constructs a type by picking all properties from type- Typeand removing properties which values are- neveror- truein type- Filter. The type- Filteris validated against a structure of- Type.
- StrictDeepPick<Type, Filter>- Constructs a type by picking set of properties, which have property values- neveror- truein type- Filter, from type- Type. The type- Filteris validated against a structure of- Type.
Key types
- OptionalKeys<Type>- Constructs a union type by picking all optional properties of object type- Type
- PickKeys<Type, Value>- Constructs a union type by picking all properties of object type- Typewhich values are assignable to type- Value
- ReadonlyKeys<Type>- Constructs a union type by picking all- readonlyproperties of object type- Type, meaning their values cannot be reassigned
- RequiredKeys<Type>- Constructs a union type by picking all required properties of object type- Type
- UnionKeys<UnionType>- Constructs a union type by picking all properties from all union members of- UnionType
- WritableKeys<Type>- Constructs a union type by picking all writable properties of object type- Type, meaning their values can be reassigned
Type checkers
- IsAny<Type>- Returns- truewhen type- Typeis- any. Otherwise returns- false
- IsExact<Type, Shape>- Returns- Typewhen type- Typeand- Shapeare identical. Otherwise returns- never
- IsNever<Type>- Returns- truewhen type- Typeis- never. Otherwise returns- false
- IsUnknown<Type>- Returns- truewhen type- Typeis- unknown. Otherwise returns- false
- IsTuple<Type>- Returns- Typewhen type- Typeis tuple. Otherwise returns- never
- NonEmptyObject<Object>- Returns- Objectwhen- Objecthas at least one key. Otherwise returns- never
- NonUnion<Type>- Returns- Typewhen- Typeis not an union. Otherwise returns- never
Arrays and Tuples
- AnyArray<Type?>- Matches- Arrayor- ReadonlyArray(- Typeis- anyby default)
- ArrayOrSingle<Type>- Matches- Typeor- Type[]
- ElementOf<Type>- Constructs a type which equals to array element type for type- Type
- Head<Type>- Constructs a type which equals to first element in type- Type
- NonEmptyArray<Type>- Matches array with at least one element of type- Type
- ReadonlyArrayOrSingle- Matches- Typeor- readonly Type[]
- Tail<Type>- Constructs a type which equals to elements but first one in type- Type
- Tuple<Type?>- Matches type constraint for tuple with elements of type- Type(- anyby default)
Change case
- CamelCase<Type>- Converts type- Typeto camel case (e.g.- camelCase)
- DeepCamelCaseProperties<Type>- Constructs a type by picking all properties from type- Typerecursively and converting all of them to camel case
Function types
- AnyFunction<Args?, ReturnType?>- Matches function type with arguments type- Args(- any[]by default) and return type- ReturnType(- anyby default)
- PredicateFunction- Matches type constraint for type guard, meaning first argument is used in return type and return type is type predicate
- PredicateType<Type>- Constructs a type which equals to narrowed type in predicate function- Type
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 for- value. When- valueisn't- never, it shows TypeScript error
- assert(condition, message?)- Matches runtime function that helps assert- condition. When- conditionis falsy, it throws an error with- Assertion Error: ${message}(message is- "no additional info provided"by default)
- createFactoryWithConstraint<Constraint>()(value)- Matches runtime function, which validates that type of- valuematches- Constraintwithout changing resulting type of- value. Ponyfill for- satisfiesoperator
- isExact<Expected>()(actual)- Matches runtime function, which validates that type of- actualequals to- Expected. Otherwise shows TypeScript error
- noop(..._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 like- awaitin- asyncfunctions, or the- .then()method on- Promises - specifically, the way that they recursively unwrap- Promises
- Capitalize<StringType>- Converts the first character in the string to an uppercase equivalent
- ConstructorParameters<Type>- Constructs a tuple or array type from the types of a constructor function type- Type
- Exclude<UnionType, ExcludedMembers>- Constructs a type by excluding from- UnionTypeall union members that are assignable to- ExcludedMembers
- Extract<Type, Union>- Constructs a type by extracting from- Typeall union members that are assignable to- Union
- InstanceType<Type>- Constructs a type consisting of the instance type of a constructor function in- Type
- Lowercase<StringType>- Converts each character in the string to the lowercase equivalent
- NonNullable<Type>- Constructs a type by excluding null and undefined from- Type
- NoInfer<Type>- Blocks inferences to the contained type. Other than blocking inferences,- NoInfer<Type>is identical to- Type
- Omit<Type, Keys>- Constructs a type by picking all properties from- Typeand then removing- Keys
- OmitThisParameter<Type>- Removes the- thisparameter from- Type. If- Typehas no explicitly declared this parameter, the result is simply- Type. Otherwise, a new function type with no this parameter is created from- Type. 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 type- Type
- Partial<Type>- Constructs a type with all properties of- Typeset to optional
- Pick<Type, Keys>- Constructs a type by picking the set of properties- Keysfrom- Type
- Readonly<Type>- Constructs a type with all properties of- Typeset to- readonly, meaning the properties of the constructed type cannot be reassigned
- Record<Keys, Type>- Constructs an object type whose property keys are- Keysand whose property values are- Type
- Required<Type>- Constructs a type consisting of all properties of- Typeset to required
- ReturnType<Type>- Constructs a type consisting of the return type of function type- Typeparameter
- ThisParameterType<Type>- Extracts the type of the- thisparameter for a function type, or- unknownif the function type has no- thisparameter
- ThisType<Type>- This utility does not return a transformed type. Instead, it serves as a marker for a contextual- thistype. Note that the- noImplicitThisflag must be enabled to use this utility
- Uncapitalize<StringType>- Converts the first character in the string to a lowercase equivalent
- Uppercase<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
