type-fest

repository·main·Indexed 12 days ago

https://github.com/sindresorhus/type-fest

A collection of essential TypeScript types designed to fill gaps in the built-in TypeScript type system. Version 5.8.0 provides advanced utility types for object manipulation (e.g., Merge, PartialDeep, RequiredDeep), string transformations (e.g., CamelCase, KebabCase), and numeric validation (e.g., Integer, NonNegative). It includes specialized types like Primitive, Class, and PackageJson, as well as complex logic utilities such as RequireExactlyOne and Simplify.

Tokens
10.4K
Snippets
20
Records
33
Agent score
96%

What's inside type-fest

  1. Extend existing types like PackageJson

    main
    If you need to extend a built-in type, such as PackageJson, to support additional configurations specific to your project, refer to the Extending existing types section in the documentation. The project avoids including every possible configuration (like PackageJsonExtras) to prevent bloat and maintain accuracy.
  2. Use type-fest in your project

    main

    Import the required types from type-fest using the import type syntax. This ensures that the types are only used during type checking and are not included in your compiled JavaScript output.

    import type {Except} from 'type-fest';
    
    type Foo = {
    	yunicorn: string;
    	radbow: boolean;
    };
    
    type FooWithoutRainbow = Except<Foo, 'rainbow'>;
    //=> {unicorn: string}
  3. Use type-fest utility types

    main

    type-fest is a collection of advanced TypeScript utility types. You can import specific types from the package to perform complex type transformations, validations, and constraints that are not available in the standard TypeScript library.

    Common categories of utilities include:

    • Object Manipulation: Merge, OmitDeep, PartialDeep, RequiredDeep, PickDeep, RenameKeys.
    • String Manipulation: CamelCase, KebabCase, PascalCase, SnakeCase, Split, Replace.
    • Array/Tuple Manipulation: FixedLengthArray, ArrayTail, TupleToUnion, UnionToTuple.
    • Validation/Constraints: NonEmptyString, Integer, LiteralUnion, Exact.
    • Advanced Logic: UnionToIntersection, ConditionalPick, Simplify.
  4. Extend the PackageJson type

    main

    Tools often add custom configurations to package.json. You can extend the base PackageJson type from type-fest using an intersection type to support these additional fields.

    import type {PackageJson as BasePackageJson} from 'type-fest';
    import type {Linter} from 'eslint';
    
    type PackageJson = BasePackageJson & {eslintConfig?: Linter.Config};
  5. Object and Collection utilities in type-fest

    main

    A wide range of utilities for manipulating object and collection types:

    Object Utilities

    • EmptyObject: Represents a strictly empty plain object {}.
    • NonEmptyObject: Represents an object with at least 1 non-optional key.
    • UnknownRecord: Represents an object with unknown values (preferred over {}).
    • Except<T, K>: Creates a type from an object type without certain keys.
    • Writable<T>: Strips readonly from a type.
    • WritableDeep<T>: Creates a deeply mutable version of an object, ReadonlyMap, ReadonlySet, or ReadonlyArray.
    • Merge<T, U>: Merges two types; keys of the second override the first.
    • ObjectMerge<T, U>: Merges two object types; keys from the second override the first.
    • MergeDeep<T, U>: Recursively merges two objects or two arrays/tuples.
    • MergeExclusive<T, U>: Creates a type with mutually exclusive keys.
    • OverrideProperties<T, U>: Overrides existing properties of a type, enforcing that the original type contains the properties being overridden.
    • RenameKeys<T, R>: Renames keys in an object type according to a map of old-to-new names.
    • RequireAtLeastOne<T, K>: Requires at least one of the given keys.
    • RequireExactlyOne<T, K>: Requires exactly one of the given keys and disallows more.
    • RequireAllOrNone<T, K>: Requires all of the given keys or none of them.
    • RequireOneOrNone<T, K>: Requires exactly one of the given keys or none of them.
    • SingleKeyObject<T>: Accepts an object with only a single key.
    • RequiredDeep<T>: Creates a deeply required version of a type.
    • PickDeep<T, K>: Picks properties from a deeply-nested object.
    • OmitDeep<T, K>: Omits properties from a deeply-nested object.
    • OmitIndexSignature<T>: Omits index signatures, leaving only explicitly defined properties.
    • PickIndexSignature<T>: Picks only index signatures, leaving out explicitly defined properties.
    • PartialDeep<T>: Creates a deeply optional version of a type.
    • PartialOnUndefinedDeep<T>: Makes all keys that accept undefined optional in a deep version of the type.
    • UndefinedOnPartialDeep<T>: Sets all optional keys to also accept undefined in a deep version of the type.
    • UnwrapPartial<T>: Reverts the Partial modifier.
    • UnwrapRequired<T>: Reverts the Required modifier.
    • ReadonlyDeep<T>: Creates a deeply immutable version of a type.
    • SetOptional<T, K>: Makes specific keys optional.
    • SetReadonly<T, K>: Makes specific keys readonly.
    • SetRequired<T, K>: Makes specific keys required.
    • SetRequiredDeep<T, K>: Makes specific keys required, supporting deeply nested key paths.
    • SetNonNullable<T, K>: Makes specific keys non-nullable.
    • SetNonNullableDeep<T, K>: Makes specified keys non-nullable (removes null and undefined) using deep key paths.
    • NonNullableDeep<T>: Recursively removes null and undefined from a type.
    • ValueOf<T, K>: Creates a union of an object's values (optionally restricted to specific keys).
    • ConditionalKeys<T, C>: Extracts keys where the value type extends a given condition.
    • ConditionalPick<T, C>: Picks keys matching a condition.
    • ConditionalPickDeep<T, C>: Picks keys recursively matching a condition.
    • ConditionalExcept<T, C>: Excludes keys matching a condition.
    • Stringified<T>: Changes all keys of a type to string.
    • Schema<T, V>: Creates a deep version of an object where property values are replaced by a given value type V.
    • Exact<T>: A type that does not allow extra properties.
    • KeysOfUnion<T>: Creates a union of all keys from a given type, including those exclusive to specific members.
    • OptionalKeysOf<T>: Extracts all optional keys.
    • RequiredKeysOf<T>: Extracts all required keys.
    • ReadonlyKeysOf<T>: Extracts all readonly keys.
    • WritableKeysOf<T>: Extracts all writable keys.
    • Spread<T, U>: Mimics the type inferred by TypeScript when using spread syntax.
    • TaggedUnion<T, K>: Creates a union of types sharing a common discriminant property.
    • ExclusifyUnion<T>: Ensures mutual exclusivity in object unions by adding other members' keys as ?: never.
  6. Basic types in type-fest

    main

    type-fest provides several basic types to match common JavaScript and TypeScript structures:

    • Primitive: Matches any primitive value.
    • Class: Matches a class.
    • Constructor: Matches a class constructor.
    • AbstractClass: Matches an abstract class.
    • AbstractConstructor: Matches an abstract class constructor.
    • TypedArray: Matches any typed array (e.g., Uint8Array, Float64Array).
    • ObservableLike: Matches a value that follows the Observable pattern.
    • LowercaseLetter: Matches any lowercase letter (a-z).
    • UppercaseLetter: Matches any uppercase letter (A-Z).
    • DigitCharacter: Matches any digit as a string ('0'-'9').
    • Alphanumeric: Matches any lowercase letter, uppercase letter, or digit.
  7. JSON and Structured Clone utilities

    main

    Utilities for working with JSON and cloning:

    JSON

    • Jsonify<T>: Transforms a type to be assignable to JsonValue.
    • Jsonifiable<T>: Matches values that can be losslessly converted to JSON.
    • JsonPrimitive<T>: Matches valid JSON primitive values.
    • JsonObject<T>: Matches a JSON object.
    • JsonArray<T>: Matches a JSON array.
    • JsonValue<T>: Matches any valid JSON value.

    Structured Clone

    • StructuredCloneable<T>: Matches values that can be losslessly cloned using structuredClone.
  8. Improved built-in TypeScript types

    main

    Stricter or more customizable versions of standard TypeScript utilities:

    • ExtendsStrict<T, U>: Customizable version of extends for checking assignability.
    • ExtractStrict<T, U>: Stricter Extract<T, U> that ensures every member of U can extract from T.
    • ExcludeStrict<T, U>: Stricter Exclude<T, U> that ensures every member of U can exclude from T.
    • ExcludeExactly<T, U>: Stricter Exclude<T, U> that excludes only when types are exactly identical.
    • ExtractExactly<T, U>: Stricter Extract<T, U> that extracts only when types are exactly identical.
  9. Array and Numeric utilities

    main

    Array

    • Arrayable<T>: Represents a value or an array of that value.
    • Includes<T, V>: Checks if an array includes a given item.
    • Join<T, S>: Joins an array of strings/numbers with a delimiter.
    • ArraySlice<T, S>: Returns an array slice of a range.
    • ArrayElement<T>: Extracts the element type of an array/tuple.
    • LastArrayElement<T>: Extracts the type of the last element.
    • FixedLengthArray<T, L>: Creates an array of type T and length L (excludes length-manipulating methods).
    • MultidimensionalArray<T, D>: Creates a multidimensional array of type T and dimension D.
    • MultidimensionalReadonlyArray<T, D>: Creates a multidimensional readonly array.
    • ReadonlyTuple<T, L>: Creates a readonly tuple of type T and length L.
    • TupleToUnion<T>: Converts a tuple/array into a union of its elements.
    • UnionToTuple<T>: Converts a union into an unordered tuple.
    • TupleToObject<T>: Transforms a tuple into an object mapping indices to types.
    • TupleOf<T, L>: Creates a tuple of length L with elements of type T.
    • SplitOnRestElement<T>: Splits an array into: elements before rest, the rest element, and elements after rest.
    • ExtractRestElement<T>: Extracts the rest element type.
    • ExcludeRestElement<T>: Creates a tuple with the rest element removed.
    • ArrayReverse<T>: Reverses the order of elements in a tuple.
    • ArrayLength<T>: Returns the length of an array.

    Numeric

    • PositiveInfinity: Matches Infinity.
    • NegativeInfinity: Matches -Infinity.
    • Finite<T>: A finite number.
    • Integer<T>: An integer number.
    • Float<T>: A non-integer number.
    • NegativeFloat<T>: A negative non-integer number.
    • Negative<T>: A negative number or bigint.
    • NonNegative<T>: A non-negative number or bigint.
    • NegativeInteger<T>: A negative integer.
    • NonNegativeInteger<T>: A non-negative integer.
    • IsNegative<T>: Boolean check for negative numbers.
    • IsFloat<T>: Boolean check for floats.
    • IsInteger<T>: Boolean check for integers.
    • GreaterThan<T, U>: Boolean check for >.
    • GreaterThanOrEqual<T, U>: Boolean check for >=.
    • LessThan<T, U>: Boolean check for <.
    • LessThanOrEqual<T, U>: Boolean check for <=.
    • Sum<T, U>: Returns the sum of two numbers.
    • Subtract<T, U>: Returns the difference.
    • Absolute<T>: Returns the absolute value.
    • StringToNumber<T>: Converts a numeric string to a number.
  10. Case conversion and Miscellaneous utilities

    main

    Case Conversion

    • CamelCase<T>: Converts string literal to camelCase.
    • CamelCasedProperties<T>: Converts top-level object properties to camelCase.
    • CamelCasedPropertiesDeep<T>: Recursively converts object properties to camelCase.
    • KebabCase<T>: Converts string literal to kebab-case.
    • KebabCasedProperties<T>: Converts top-level object properties to kebab-case.
    • KebabCasedPropertiesDeep<T>: Recursively converts object properties to kebab-case.
    • PascalCase<T>: Converts string literal to PascalCase.
    • PascalCasedProperties<T>: Converts top-level object properties to PascalCase.
    • PascalCasedPropertiesDeep<T>: Recursively converts object properties to PascalCase.
    • SnakeCase<T>: Converts string literal to snake_case.
    • SnakeCasedProperties<T>: Converts top-level object properties to snake_case.
    • SnakeCasedPropertiesDeep<T>: Recursively converts object properties to snake_case.
    • ScreamingSnakeCase<T>: Converts string literal to SCREAMING_SNAKE_CASE.
    • DelimiterCase<T, D>: Converts string literal to a custom delimiter casing.
    • DelimiterCasedProperties<T, D>: Converts top-level object properties to custom delimiter casing.
    • DelimiterCasedPropertiesDeep<T, D>: Recursively converts object properties to custom delimiter casing.

    Miscellaneous

    • GlobalThis: Declare locally scoped properties on globalThis.
    • PackageJson: Type for package.json files (including TypeScript and Yarn fields).
    • TsConfigJson: Type for tsconfig.json files.
  11. Async and String utilities

    main

    Async

    • Promisable<T>: Represents a value or a PromiseLike version of that value.
    • AsyncReturnType<T>: Unwraps the return type of a function that returns a Promise.
    • Asyncify<T>: Creates an async version of a function by boxing the return type in Promise.

    String

    • Trim<T>: Removes leading/trailing spaces from a string literal.
    • Split<T, S>: Represents an array of strings split by a character or set.
    • Words<T>: Splits a string into words (similar to Lodash _.words()).
    • Replace<T, R>: Represents a string with matches replaced.
    • StringSlice<T, S>: Returns a string slice of a range (like String#slice()).
    • StringRepeat<T, N>: Returns a string containing N copies of the string.
    • RemovePrefix<T, P>: Removes a specified prefix.
    • RemoveSuffix<T, S>: Removes a specified suffix.
    • StringToArray<T>: Returns an array of characters from a string.
    • StringLength<T>: Returns the length of a string.