type-fest project
Full project type-check throughput, including module graph setup and cross-file type analysis.
tsz is 2.3x faster 16758 lines 467 KB
Timing
README
A collection of essential TypeScript types
Sindre Sorhus' open source work is supported by the community
Special thanks to:
Many of the types here should have been built-in. You can help by suggesting some of them to the TypeScript project.
Either add this package as a dependency or copy-paste the needed types. No credit required. 👌
PR welcome for additional commonly needed types and docs improvements. Read the contributing guidelines first.
Help wanted with reviewing proposals and pull requests.
Install
npm install type-fest
Requires TypeScript >=5.9, ESM, and {strict: true} in your tsconfig.
[!NOTE] This readme shows the current development version. For docs about the latest version, see the npm page.
You may also like my ts-extras package which provides runtime functions for some of these types.
Usage
import type {Except} from 'type-fest';
type Foo = {
unicorn: string;
rainbow: boolean;
};
type FooWithoutRainbow = Except<Foo, 'rainbow'>;
//=> {unicorn: string}
API
Click the type names for complete docs.
Basic
Primitive- Matches any primitive value.Class- Matches aclass.Constructor- Matches aclassconstructor.AbstractClass- Matches anabstract class.AbstractConstructor- Matches anabstract classconstructor.TypedArray- Matches any typed array, likeUint8ArrayorFloat64Array.ObservableLike- Matches a value that is like an Observable.LowercaseLetter- Matches any lowercase letter in the basic Latin alphabet (a-z).UppercaseLetter- Matches any uppercase letter in the basic Latin alphabet (A-Z).DigitCharacter- Matches any digit as a string ('0'-'9').Alphanumeric- Matches any lowercase letter (a-z), uppercase letter (A-Z), or digit ('0'-'9') in the basic Latin alphabet.
Utilities
EmptyObject- Represents a strictly empty plain object, the{}value.NonEmptyObject- Represents an object with at least 1 non-optional key.UnknownRecord- Represents an object withunknownvalue. You probably want this instead of{}.UnknownArray- Represents an array withunknownvalue.UnknownMap- Represents a map withunknownkey and value.UnknownSet- Represents a set withunknownvalue.Except- Create a type from an object type without certain keys.Writable- Create a type that stripsreadonlyfrom the given type. Inverse ofReadonly<T>.WritableDeep- Create a deeply mutable version of anobject/ReadonlyMap/ReadonlySet/ReadonlyArraytype. The inverse ofReadonlyDeep<T>. UseWritable<T>if you only need one level deep.Merge- Merge two types into a new type. Keys of the second type overrides keys of the first type.ObjectMerge- Merge two object types into a new object type, where keys from the second override keys from the first.MergeDeep- Merge two objects or two arrays/tuples recursively into a new type.MergeExclusive- Create a type that has mutually exclusive keys.OverrideProperties- Override existing properties of the given type. Similar toMerge, but enforces that the original type has the properties you want to override.RequireAtLeastOne- Create a type that requires at least one of the given keys, while keeping the remaining keys as is.RequireExactlyOne- Create a type that requires exactly one of the given keys and disallows more, while keeping the remaining keys as is.RequireAllOrNone- Create a type that requires all of the given keys or none of the given keys, while keeping the remaining keys as is.RequireOneOrNone- Create a type that requires exactly one of the given keys or none of the given keys, while keeping the remaining keys as is.SingleKeyObject- Create a type that only accepts an object with a single key.RequiredDeep- Create a deeply required version of another type.PickDeep- Pick properties from a deeply-nested object.OmitDeep- Omit properties from a deeply-nested object.OmitIndexSignature- Omit any index signatures from the given object type, leaving only explicitly defined properties.PickIndexSignature- Pick only index signatures from the given object type, leaving out all explicitly defined properties.PartialDeep- Create a deeply optional version of another type.PartialOnUndefinedDeep- Create a deep version of another type where all keys acceptingundefinedtype are set to optional.UndefinedOnPartialDeep- Create a deep version of another type where all optional keys are set to also acceptundefined.UnwrapPartial- Revert thePartialmodifier on an object type.ReadonlyDeep- Create a deeply immutable version of another type.LiteralUnion- Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union.Tagged- Create a tagged type that can support multiple tags and per-tag metadata.UnwrapTagged- Get the untagged portion of a tagged type created withTagged.InvariantOf- Create an invariant type, which is a type that does not accept supertypes and subtypes.SetOptional- Create a type that makes the given keys optional, while keeping the remaining keys as is.SetReadonly- Create a type that makes the given keys readonly, while keeping the remaining keys as is.SetRequired- Create a type that makes the given keys required, while keeping the remaining keys as is.SetRequiredDeep- Create a type that makes the given keys required, with support for deeply nested key paths, while keeping the remaining keys as is.SetNonNullable- Create a type that makes the given keys non-nullable, while keeping the remaining keys as is.SetNonNullableDeep- Create a type that makes the specified keys non-nullable (removesnullandundefined), supports deeply nested key paths, and leaves all other keys unchanged.NonNullableDeep- Recursively removesnullandundefinedfrom the specified type.ValueOf- Create a union of the given object's values, and optionally specify which keys to get the values from.ConditionalKeys- Extract the keys from a type where the value type of the key extends the givenCondition.ConditionalPick- Pick keys from the shape that matches the givenCondition.ConditionalPickDeep- Pick keys recursively from the shape that matches the given condition.ConditionalExcept- Exclude keys from a shape that matches the givenCondition.UnionToIntersection- Convert a union type to an intersection type.LiteralToPrimitive- Given a literal type return the primitive type it belongs to, orneverif it's not a primitive.LiteralToPrimitiveDeep- LikeLiteralToPrimitiveexcept it converts literal types inside an object or array deeply.Stringified- Create a type with the keys of the given type changed tostringtype.IterableElement- Get the element type of anIterable/AsyncIterable. For example,Array,Set,Map, generator, stream, etc.Entry- Create a type that describes a single key-value pair produced when calling a collection’sentriesmethod.Entries- Create a type that describes the key-value pairs produced when calling a collection’sentriesmethod.SetReturnType- Create a function type with a return type of your choice and the same parameters as the given function type.SetParameterType- Create a function that replaces some parameters with the given parameters.Simplify- Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.SimplifyDeep- Deeply simplifies an object type.Get- Get a deeply-nested property from an object using a key path, like Lodash's.get()function.KeyAsString- Get keys of the given type as strings.Schema- Create a deep version of another object type where property values are recursively replaced into a given value type.Exact- Create a type that does not allow extra properties, meaning it only allows properties that are explicitly declared.KeysOfUnion- Create a union of all keys from a given type, even those exclusive to specific union members.OptionalKeysOf- Extract all optional keys from the given type.HasOptionalKeys- Returns a boolean for whether the given type has any optional fields.RequiredKeysOf- Extract all required keys from the given type.HasRequiredKeys- Returns a boolean for whether the given type has any required fields.ReadonlyKeysOf- Extract all readonly keys from the given type.HasReadonlyKeys- Returns a boolean for whether the given type has any readonly fields.WritableKeysOf- Extract all writable keys from the given type.HasWritableKeys- Returns a boolean for whether the given type has any writable fields.Spread- Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.IsEqual- Returns a boolean for whether the two given types are equal.TaggedUnion- Create a union of types that share a common discriminant property.IntRange- Generate a union of numbers between a specified start (inclusive) and end (exclusive), with an optional step.IntClosedRange- Generate a union of numbers between a specified start and end (both inclusive), with an optional step.ArrayIndices- Provides valid indices for a constant array or tuple.ArrayValues- Provides all values for a constant array or tuple.ArraySplice- Create a new array type by adding or removing elements at a specified index range in the original array.ArrayTail- Extract the type of an array or tuple minus the first element.SetFieldType- Create a type that changes the type of the given keys.Paths- Generate a union of all possible paths to properties in the given object.SharedUnionFields- Create a type with shared fields from a union of object types.SharedUnionFieldsDeep- Create a type with shared fields from a union of object types, deeply traversing nested structures.AllUnionFields- Create a type with all fields from a union of object types.DistributedOmit- Omits keys from a type, distributing the operation over a union.DistributedPick- Pick keys from a type, distributing the operation over a union.And- Returns a boolean for whether two given types are bothtrue.Or- Returns a boolean for whether either of two given types istrue.Xor- Returns a boolean for whether only one of two given types istrue.AndAll- Returns a boolean for whether all of the given elements aretrue.OrAll- Returns a boolean for whether any of the given elements istrue.AllExtend- Returns a boolean for whether every element in an array type extends another type.SomeExtend- Returns a boolean for whether some element in an array type extends another type.NonEmptyTuple- Matches any non-empty tuple.NonEmptyString- Matches any non-empty string.FindGlobalType- Tries to find the type of a global with the given name.FindGlobalInstanceType- Tries to find one or more types from their globally-defined constructors.ConditionalSimplify- Simplifies a type while including and/or excluding certain types from being simplified.ConditionalSimplifyDeep- Recursively simplifies a type while including and/or excluding certain types from being simplified.ExclusifyUnion- Ensure mutual exclusi
...