Ts essentials project
A broad utility-type toolkit covering recursive JSON shapes, deep readonly, and strict-null helpers; stresses mapped/conditional evaluation with recursive object types.
tsgo is 1.1x faster 3903 lines 87 KB
Timing
README
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
⚠️ Make sure you add 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 toUnion- [
InstanceType<Type>](https://www.typescriptlang.org/docs/handbook/utility-type
...