npm type-fest 6.0.0

37 minutes ago

Summary

This is a huge release! 120 new types. All open issues resolved. A huge number of performance and correctness fixes.

Breaking

  • Require TypeScript 6 9ec2593
  • Require Node.js 22 9ec2593
  • Require exactOptionalPropertyTypes: true in your tsconfig 82f2b44
    • The types no longer have compatibility logic for exactOptionalPropertyTypes: false. Disabling it is unsupported.
  • Reminder: type-fest requires strict, which is the default since TypeScript 6. Do not set it to false.
  • Remove the deprecated IfAny, IfNever, IfUnknown, IfNull, and IfEmptyObject types. Use If with the matching Is* type. 6fc1861
  • Remove the deprecated ReadonlyTuple type. Use Readonly<TupleOf<Length, Element>>. 6fc1861
  • CamelCase, PascalCase, KebabCase, SnakeCase, ScreamingSnakeCase, DelimiterCase, Words, and their *CasedProperties / *CasedPropertiesDeep types: Enable splitOnPunctuation by default. ebc42e5
    • KebabCase<'div.card::after'> is now 'div-card-after' (was 'div.card::after').
    • A leading $ is now removed: CamelCase<'$foo'> is 'foo'.
  • CamelCase / PascalCase (and their *CasedProperties types): Disable splitOnNumbers by default 976bd26
    • CamelCase<'p2p_network'> is now 'p2pNetwork' (was 'p2PNetwork'). The other case types already used false.
  • CamelCase / PascalCase (and their *CasedProperties types): Enable preserveLeadingUnderscores by default 8144ba1
    • CamelCase<'_id'> is now '_id' (was 'id'). This matches the camelcase package.
    • PascalCase<'_foo_bar'> is now '_FooBar' (was 'FooBar').
  • Words: With splitOnPunctuation: false, punctuation now stays inside the word: Words<'hello:world', {splitOnPunctuation: false}> is ['hello:world'] (was ['hello', ':world']) 9f2ad66
  • PartialDeep: Enable recurseIntoArrays by default. ab0e23d
    • The elements of arrays and tuples are now deeply partial, and the fixed elements of tuples become optional.
    • allowUndefinedInNonTupleArrays: true now works alone. Before, it also needed recurseIntoArrays: true.
  • PartialOnUndefinedDeep: Enable recurseIntoArrays by default 939abe3
  • ExtendsStrict: Enable strictAny by default, so ExtendsStrict<any, number> is now false. Pass {strictAny: false} to get the old behavior. b2f7ed4
  • Split: Rename the strictLiteralChecks option to strict bc38ddb
  • StringToArray: Replace the mapNonLiteralsDirectly option with strict, which has the opposite meaning. {mapNonLiteralsDirectly: true} is now {strict: false}. b61e528
    • The old option names now give a compiler error.
  • ReadonlyDeep: Convert Date to the new ReadonlyDate type, which has no set* methods. WritableDeep converts it back to Date. c533251
  • TsConfigJson: Remove the options and values that TypeScript 5.5 removed and that TypeScript 6.0 deprecated. 393c093 0716fa8 4e54420 65b2db8
  • Predicates now return false instead of never when an input is never 9ec1de5
    • This applies to IsEmptyObject, IsFloat, IsInteger, IsNegative, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, Includes, IsOptionalKeyOf, IsRequiredKeyOf, IsReadonlyKeyOf, and IsWritableKeyOf.
    • If you checked the result with IsNever or [Result] extends [never], check for false instead.
  • IsNull / IsUndefined: Return false for any and never (was true) 349271e 750177a 65fc2eb
  • IsOptionalKeyOf / IsRequiredKeyOf / IsReadonlyKeyOf / IsWritableKeyOf: Read a literal key of an index signature like the index signature, and read an any object like Record<PropertyKey, any> 62df5d9 5a2e786
    • IsOptionalKeyOf<Record<string, number>, 'x'> is now true (was false), and IsRequiredKeyOf is now false.
    • IsReadonlyKeyOf<{readonly [key: string]: number}, 'x'> is now true (was false).
    • With an any object, the result was never. Now a literal key is optional and writable, so IsOptionalKeyOf<any, 'a'> and IsWritableKeyOf<any, 'a'> are true, and IsRequiredKeyOf<any, 'a'> and IsReadonlyKeyOf<any, 'a'> are false. A string, number, or symbol key is required, and an any key gives boolean.
  • FixedLengthArray: Return never for a non-literal length, like number. Use a normal array type for an unknown length. 88281fe
  • Finite / NonNegative: Return never for the wide number type (was number) 23e295f
  • NonNegative / Negative: Reject Infinity and -Infinity (for example 1e999) 608026d
  • Jsonifiable: Reject values typed object, because they can contain anything 92aba94
  • ConditionalPickDeep: Match any and never values like ConditionalKeys. A never value is no longer picked, and an any value is now picked. 02aef94
  • Other result changes that you can see in existing code:
    • Simplify: Keep functions, class constructors, and branded primitives as is. Simplify<() => void> was {}. 28b9f8e 7d0a323
    • Merge: Keep the call signatures of the input 166b209
    • The deep types (PartialDeep, ReadonlyDeep, RequiredDeep, and others) no longer recurse into DOM nodes, like HTMLElement e379753
    • Entries / Entry: Pair each key with its own value. Entry<{a: 1; b: 'x'}> is now ['a', 1] | ['b', 'x'] (was ['a' | 'b', 1 | 'x']). 34d036f
    • ValueOf: Read the values of every union member. ValueOf<{a: 1} | {b: 2}> is now 1 | 2 (was never). 6a0de70 1a2e90a
    • Get: Return undefined for the union members that do not have the key. Get<{a: 1} | {b: 2}, 'a'> is now 1 | undefined (was unknown). cc955bd
    • LiteralToPrimitiveDeep: Keep tuples as tuples. [1] becomes [number] (was number[]). 8173c2c
    • LiteralToPrimitive: Return any for any 65fc2eb
    • MultidimensionalArray / MultidimensionalReadonlyArray: Allow leaf values at all levels when the dimension is not known 762b656
    • RemovePrefix / RemoveSuffix: Return string when a non-literal input cannot contain the affix. RemovePrefix<`user_${string}`, 'admin_'> is now string (was `user_${string}`). b8c6ef2 1fbd1d2
    • IsEmptyObject: Return false for object (was true) and for any (was boolean) 43c237d 9ec1de5
    • HasRequiredKeys: Return false for index signatures, arrays without required elements, and any (was true) 1c184e6
    • IsFloat: Return boolean for any (was false) cdf0ede
    • Asyncify: Keep the return type of each function in a union 1b374de
    • SingleKeyObject: Return never for boolean (was boolean), and return broad object types, like object and Record<string, number>, as is (was never) 2745e8f 43c237d
    • StringToArray: A non-literal part gives string elements, because each character does not always match the type of the whole part. StringToArray<Lowercase<string>> is now string[] (was Lowercase<string>[]). b9337f2
  • Opaque and UnwrapOpaque are still deprecated, and v7 will remove them. Use Tagged and UnwrapTagged. 62c465e

New types

Improvements

  • PartialDeep, ReadonlyDeep, RequiredDeep, WritableDeep, NonNullableDeep: Add a keep option to leave the matching types as is c09e9ec
  • ConditionalKeys, ConditionalPick, ConditionalExcept: Add a strict option, so the whole union value must match the condition 1f61c5d
  • Paths: Add the valueType, recurseIntoArrays, requiredOnly, and maxCircularDepth options 2c5d371 4cbbaca e17546c
  • ConditionalPickDeep: Recurse into optional object properties 6e9ce0b
  • GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual: Support bigint d2fec83
  • TypedArray: Add a Buffer type parameter 733ccc5
  • Get: Accept numbers in paths, non-literal number indexes on arrays and tuples, and Paths<T> for a generic T d02234b 801fa7f 1c3ff80 edbbd28
  • PickDeep, SetRequiredDeep, SetNonNullableDeep: Accept paths deeper than Paths lists f339d83 dac3375
  • SetOptional, SetRequired, SetReadonly, SetNonNullable, SetFieldType, Except, RequireAtLeastOne, RequireExactlyOne, RequireOneOrNone, RequireAllOrNone, ValueOf: Accept keys of any union member 6f4eaa7 3c49f2a b4fd7ce 1a2e90a
  • DistributedOmit: Accept keys that are not in the type c4f0f20
  • Class, Constructor, AbstractClass, AbstractConstructor: Accept readonly argument tuples cbc9e15
  • IntRange, IntClosedRange: Support enum and non-literal bounds 7a9c7e8
  • SharedUnionFieldsDeep, SimplifyDeep, ConditionalSimplifyDeep, Schema, RequiredDeep, NonNullableDeep: Support recursive array element types e2575dc 0d4ce83 41b3eaa 3c27bdd 0b7a150
  • StructuredCloneable: Accept readonly dates, shared array buffers, and BigInt wrapper objects 7fd58f4 e5fc826 38f3730
  • PackageJson: Add gypfile and libc, and accept array funding, nested exports and imports fallback arrays, and required peer dependency metadata 65b2db8 df9f758 e69ce64
  • TsConfigJson: Add the ES2016.Intl, ESNext.Date, ESNext.SharedMemory, and ESNext.TypedArrays lib values, and change generateTrace to a directory string 65b2db8
  • Many numeric and string types accept branded primitives and enum members, for example Sum, Subtract, GreaterThan, ArraySlice, ArraySplice, TupleOf, Split, Replace, Trim, Join, and StringRepeat d13a397 43e8c5c ddb0c2b 930c7b9 a65f404 cc4c6da ce79ec7 ad8f97e 7ddfc14 7e8cb22 2a42f6f
  • Improve type-checking performance, especially for Get, PickDeep, OmitDeep, and the Set*Deep types with large object types f5666bc 8a15ef4 307c128

Fixes

  • Jsonify: Omit properties based on their toJSON() result, keep the length and holes of optional tuples, keep the elements of tagged tuples, keep literal keys next to an index signature, and fix infinite recursion with JsonValue b0975a1 02adfbc c057ca6 7237dd9 c1c084f 666a414
  • Exact: Fix union inputs, index signatures with object values, and nested objects under optional or nullable properties 63c8a22 150166b c89866b
  • PickDeep: Keep union members that the path cannot go into, and merge several paths into the same tuple 2c7c89b a597928
  • OmitDeep: Keep a tuple or array unchanged for an out-of-bounds, negative, or noncanonical index e3ef5b7 237f41c
  • ConditionalKeys: Keep declared keys when the object has an index signature 6328ee0
  • ConditionalPick, ConditionalExcept, OmitDeep, SharedUnionFields, AllUnionFields, ExclusifyUnion, RequireAllOrNone, RequireExactlyOne, RequireOneOrNone: Keep declared fields next to an index signature 8818aae 873cd42 0a4d9a3 96ecce9 0f022d2 3934944
  • Merge, Spread, MergeDeep: Fix tuples, optional tuple positions, readonly properties, symbols, and numeric index signatures 2fabdf5
  • MergeExclusive: Fix union members facd526
  • Replace: Fix non-literal search strings 37a2727
  • Join: Fix empty rest elements, and keep a union delimiter the same in the whole result e7b9c10 d7e5cae
  • KeysOfUnion: Accept keys narrowed with keyof on generic types baf01ca
  • IsLiteral: Fix an unresolved result for template literal types intersected with {} c73a956
  • IsLiteral, IsNumericLiteral, IsStringLiteral: Fix wrapped results in generic code 691aac6
  • ArraySlice, ArraySplice, ArrayIndices, ExcludeRestElement, SplitOnRestElement, TupleOf: Fix optional elements, readonly arrays, negative indices, and unknown lengths 7c8f174
  • GreaterThan, LessThan, Sum, Subtract, Absolute, IntRange, IsFloat, IsInteger: Fix decimal fractions, branded numbers, and enum members cdf0ede
  • Case conversion types: Fix non-literal, branded, Unicode, and mixed union inputs 9f2ad66 50e46c1
  • Deep types: Keep tuples, functions, receivers, and built-in types 8173c2c
  • SetParameterType, SetReturnType, Asyncify: Keep this parameters and readonly rest parameters 65fc2eb f8d43f2
  • UnwrapTagged: Remove all tags from a type with several tags 65fc2eb cbb9188
  • TaggedUnion: Leave missing dictionary entries out of the result afc29e0
  • FindGlobalType: Keep the found globals when other names are missing 1750664
  • ExcludeStrict: Allow exclusions from overlapping union members 777f4e9
  • Writable: Fix numeric enum keys, and keep readonly containers when no keys are selected 92d0c07 db9af8a
  • Many object types: Match numeric keys and their string forms (0 and '0'), and string enum keys, consistently a99e994 0adbfbb 9ec5640 f5b6178

Migration guide

TypeScript and tsconfig

Upgrade to TypeScript 6 or later, and enable exactOptionalPropertyTypes in your tsconfig. strict does not enable it.

{
	"compilerOptions": {
		"exactOptionalPropertyTypes": true
	}
}

strict is the default since TypeScript 6, so you can remove "strict": true. Do not set it to false.

Removed If* types

Use If with the matching Is* type. If has no default branches, so give both.

-import type {IfAny} from 'type-fest';
+import type {If, IsAny} from 'type-fest';

-type Result = IfAny<T, 'any', 'not any'>;
+type Result = If<IsAny<T>, 'any', 'not any'>;
Removed Replacement
IfAny<T, A, B> If<IsAny<T>, A, B>
IfNever<T, A, B> If<IsNever<T>, A, B>
IfUnknown<T, A, B> If<IsUnknown<T>, A, B>
IfNull<T, A, B> If<IsNull<T>, A, B>
IfEmptyObject<T, A, B> If<IsEmptyObject<T>, A, B>

If you used the default true and false branches, like IfAny<T>, use the Is* type directly: IsAny<T>.

Note: IsNull<any> is now false. IfNull<any> returned the first branch.

ReadonlyTuple

-import type {ReadonlyTuple} from 'type-fest';
+import type {TupleOf} from 'type-fest';

-type FencingTeam = ReadonlyTuple<string, 3>;
+type FencingTeam = Readonly<TupleOf<3, string>>;
//=> readonly [string, string, string]

Note: The order of the type arguments is different.

Case conversion defaults

The case conversion types now split on punctuation by default. CamelCase and PascalCase also keep leading underscores, and do not split on numbers.

import type {CamelCase, KebabCase} from 'type-fest';

type A = CamelCase<'foo-bar:baz'>;
//=> v5: 'fooBar:baz'
//=> v6: 'fooBarBaz'

type B = CamelCase<'_id'>;
//=> v5: 'id'
//=> v6: '_id'

type C = CamelCase<'p2p_network'>;
//=> v5: 'p2PNetwork'
//=> v6: 'p2pNetwork'

type D = KebabCase<'div.card::after'>;
//=> v5: 'div.card::after'
//=> v6: 'div-card-after'

To get the v5 results, give the old defaults as options:

import type {CamelCase, CamelCasedProperties, KebabCase} from 'type-fest';

type OldCamelCaseOptions = {
	splitOnPunctuation: false;
	splitOnNumbers: true;
	preserveLeadingUnderscores: false;
};

type A = CamelCase<'foo-bar:baz', OldCamelCaseOptions>;
//=> 'fooBar:baz'

type B = CamelCasedProperties<{_id: string}, OldCamelCaseOptions>;
//=> {id: string}

type C = KebabCase<'div.card::after', {splitOnPunctuation: false}>;
//=> 'div.card::after'

recurseIntoArrays

PartialDeep and PartialOnUndefinedDeep now also change the elements of arrays and tuples.

import type {PartialDeep} from 'type-fest';

type Settings = {
	layers: Array<{name: string}>;
	position: [x: number, y: number];
};

type A = PartialDeep<Settings>;
//=> v5: {layers?: Array<{name: string}>; position?: [x: number, y: number]}
//=> v6: {layers?: Array<{name?: string}>; position?: [x?: number, y?: number]}

To keep arrays and tuples as is, pass {recurseIntoArrays: false}:

-type A = PartialDeep<Settings>;
+type A = PartialDeep<Settings, {recurseIntoArrays: false}>;

If you passed {recurseIntoArrays: true}, you can remove it.

Split and StringToArray options

-type A = Split<Value, '.', {strictLiteralChecks: false}>;
+type A = Split<Value, '.', {strict: false}>;

-type B = StringToArray<Value, {mapNonLiteralsDirectly: true}>;
+type B = StringToArray<Value, {strict: false}>;

ReadonlyDeep and Date

ReadonlyDeep now turns a Date into a ReadonlyDate, which has no set* methods. A ReadonlyDate is not assignable to Date.

import type {ReadonlyDeep} from 'type-fest';

type Event = ReadonlyDeep<{start: Date}>;
//=> v5: {readonly start: Date}
//=> v6: {readonly start: ReadonlyDate}

If you give the dates to code that expects a Date, change that code to accept a ReadonlyDate, or keep dates as is with the keep option:

type Event = ReadonlyDeep<{start: Date}, {keep: Date}>;
//=> {readonly start: Date}

Predicates with never and any

Predicates that returned never for a never input now return false. A conditional type that reads the result now goes to the false branch. Before, it gave never.

import type {IsFloat, IsNull} from 'type-fest';

type A = IsFloat<never>;
//=> v5: never
//=> v6: false

type B = IsNull<any>;
//=> v5: true
//=> v6: false

TsConfigJson

These compilerOptions were removed, because TypeScript removed them or TypeScript 6 deprecated them:

  • baseUrl
  • outFile
  • downlevelIteration
  • charset
  • importsNotUsedAsValues
  • preserveValueImports
  • keyofStringsOnly
  • noImplicitUseStrict
  • noStrictGenericChecks
  • suppressExcessPropertyErrors
  • suppressImplicitAnyIndexErrors
  • watch
  • fallbackPolling
  • watchDirectory
  • watchFile (use watchOptions)
  • listFilesOnly

These values were removed:

  • module: 'None', 'AMD', 'UMD', 'System'
  • moduleResolution: 'Classic', 'Node', 'Node10'
  • target: 'ES3', 'ES5'
  • lib: 'ES2022.SharedMemory' (TypeScript has no lib with this name)
  • alwaysStrict, esModuleInterop, and allowSyntheticDefaultImports accept only true.

The TsConfigJson.CompilerOptions.ImportsNotUsedAsValues, FallbackPolling, WatchDirectory, and WatchFile types were also removed. Use the types in TsConfigJson.WatchOptions instead of the last three.


v5.10.0...v6.0.0

Don't miss a new type-fest release

NewReleases is sending notifications on new releases.