-
-
Notifications
You must be signed in to change notification settings - Fork 723
Add RenameKeys type
#1435
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
materwelonDhruv
wants to merge
22
commits into
sindresorhus:main
Choose a base branch
from
materwelonDhruv:add-rename-key
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+381
−0
Open
Add RenameKeys type
#1435
Changes from 16 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
d001faa
feat: add `RenameKey` type
materwelonDhruv 80c9aec
feat: add `RenameKeys` type
materwelonDhruv 0eddd05
fix(lint): lint error in import statement
materwelonDhruv 229c206
fix: reject key collisions and optional map entries in `RenameKey`/`R…
materwelonDhruv 9c3e2d3
tests: cover `RenameKey`/`RenameKeys` edge cases and rejections
materwelonDhruv 889d438
fix: linter needs enable statements after file-level disable statements
materwelonDhruv a407f21
fix: various issues
materwelonDhruv 92b4a86
chore: update readme
materwelonDhruv 6bf4632
fix: lint issues
materwelonDhruv d556969
feat: add reliable merging behavior
materwelonDhruv c90f79b
chore: remove `RenameKey` type
materwelonDhruv 4f71ea3
refactor: use the existing internal type for this
materwelonDhruv c4a9851
refactor: make option keys no-op instead of fail
materwelonDhruv 8da94ac
refactor: allow unions distributing their types on rename
materwelonDhruv c09e705
fix: correct modifier handling on merged targets
materwelonDhruv bbba36a
fix: unsynced readme desc
materwelonDhruv 231568a
fix: incorrect optional behavior with EOPT off
materwelonDhruv 3b6b979
fix: make non-literal targets no op instead of produce a `never`
materwelonDhruv 438f46f
refactor: simplify the type's impl + some more tests
materwelonDhruv 8615b9b
Merge remote-tracking branch 'upstream/main' into add-rename-key
materwelonDhruv aafd4ea
fix: updated API
materwelonDhruv 2b3db9a
refactor: the source value type is not needed anymore
materwelonDhruv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| import type {IsLiteral} from './is-literal.d.ts'; | ||
| import type {IsAny} from './is-any.d.ts'; | ||
| import type {IsNever} from './is-never.d.ts'; | ||
| import type {IsReadonlyKeyOf} from './is-readonly-key-of.d.ts'; | ||
| import type {IsOptionalKeyOf} from './is-optional-key-of.d.ts'; | ||
| import type {OmitIndexSignature} from './omit-index-signature.d.ts'; | ||
| import type {PickIndexSignature} from './pick-index-signature.d.ts'; | ||
| import type {Simplify} from './simplify.d.ts'; | ||
| import type {IsExactOptionalPropertyTypesEnabled} from './internal/type.d.ts'; | ||
|
|
||
| /** | ||
| Rename keys in an object type according to a map of old-to-new names. Keys absent from the map are returned unchanged. The value type, the optional modifier, and the readonly modifier are applied to the new key. | ||
|
|
||
| Distributes over a union of rename maps and over a union of source types. | ||
|
|
||
| When multiple source keys map to the same target, the target's value type is the union of the contributors' value types. The target is optional only when every contributor is optional, and is `readonly` when any contributor is `readonly`. With `exactOptionalPropertyTypes` disabled, the value type of a mixed-optionality merge also includes `undefined`. | ||
|
|
||
| A union target distributes, producing one output key per member. For example, `{a: 'b' | 'c'}` on a source with `a: string` produces both `b: string` and `c: string`. | ||
|
|
||
| A rename map entry whose key is not a property of the source type is ignored, matching the result of `Omit`. The optional modifier on a rename map entry is ignored, so `{a?: 'alpha'}` produces the same result as `{a: 'alpha'}`. | ||
|
|
||
| Returns `never` in the following cases. | ||
| - A rename map entry's value is not a literal `PropertyKey` (rejects primitives like `string`). | ||
| - The source type is `any` or `never`. | ||
|
|
||
| @example | ||
| ``` | ||
| import type {RenameKeys} from 'type-fest'; | ||
|
|
||
| type User = { | ||
| id: string; | ||
| firstName: string; | ||
| createdAt: Date; | ||
| }; | ||
|
|
||
| type Renamed = RenameKeys<User, {firstName: 'first_name'; createdAt: 'created_at'}>; | ||
| //=> {id: string; first_name: string; created_at: Date} | ||
| ``` | ||
|
|
||
| @example | ||
| ``` | ||
| import type {RenameKeys} from 'type-fest'; | ||
|
|
||
| type SearchInput = { | ||
| textQuery: string; | ||
| voiceQuery: Blob; | ||
| imageQuery: File; | ||
| }; | ||
|
|
||
| type Normalized = RenameKeys<SearchInput, {textQuery: 'query'; voiceQuery: 'query'; imageQuery: 'query'}>; | ||
| //=> {query: string | Blob | File} | ||
| ``` | ||
|
|
||
| @category Object | ||
| */ | ||
| export type RenameKeys< | ||
| BaseType, | ||
| RenameMap extends Record<PropertyKey, PropertyKey>, | ||
| > = IsAny<BaseType> extends true | ||
| ? never | ||
| : IsNever<BaseType> extends true | ||
| ? never | ||
| : BaseType extends BaseType // Distribute over union sources. | ||
| ? BaseType extends object | ||
| ? RenameMap extends RenameMap // Distribute over union maps. | ||
| ? _AllTargetsAreLiterals<Required<RenameMap>> extends true | ||
| ? _RenameOnce<BaseType, Required<RenameMap>> | ||
| : never | ||
| : never | ||
| : never | ||
| : never; | ||
|
|
||
| type _AllTargetsAreLiterals<RenameMap> = [ | ||
| { | ||
| [Key in keyof RenameMap]: IsLiteral<RenameMap[Key]>; | ||
| }[keyof RenameMap], | ||
| ] extends [true] | ||
| ? true | ||
| : false; | ||
|
|
||
| type _TargetOf<SourceKey, RenameMap> = | ||
| SourceKey extends keyof RenameMap | ||
| ? RenameMap[SourceKey] extends PropertyKey | ||
| ? RenameMap[SourceKey] | ||
| : SourceKey | ||
| : SourceKey; | ||
|
|
||
| // `BaseType[Key]` on an optional key includes `undefined`. With EOPT on, | ||
| // `Required<Pick>` strips that `undefined`. With EOPT off, the natural | ||
| // index access retains it, so mixed-optionality merges include it. | ||
| type _NewValue<BaseType, Key extends keyof BaseType> = | ||
| IsExactOptionalPropertyTypesEnabled extends true | ||
| ? Required<Pick<BaseType, Key>>[Key] | ||
| : BaseType[Key]; | ||
|
|
||
| // Targets where at least one contributing source key is readonly. | ||
| type _ReadonlyTargets<BaseType extends object, RenameMap> = { | ||
| [Key in keyof BaseType]: Key extends keyof BaseType | ||
| ? IsReadonlyKeyOf<BaseType, Key> extends true | ||
| ? _TargetOf<Key, RenameMap> | ||
| : never | ||
| : never; | ||
| }[keyof BaseType]; | ||
|
|
||
| // Targets where at least one contributing source key is required. | ||
| type _RequiredTargets<BaseType extends object, RenameMap> = { | ||
| [Key in keyof BaseType]: Key extends keyof BaseType | ||
| ? IsOptionalKeyOf<BaseType, Key> extends false | ||
| ? _TargetOf<Key, RenameMap> | ||
| : never | ||
| : never; | ||
| }[keyof BaseType]; | ||
|
|
||
| // `Target extends Target` distributes per union member. | ||
| type _RouteTarget<Target, ReadOnly, Required, NeedReadonly extends boolean, NeedRequired extends boolean> = | ||
| Target extends Target | ||
| ? (Target extends ReadOnly ? true : false) extends NeedReadonly | ||
| ? (Target extends Required ? true : false) extends NeedRequired | ||
| ? Target | ||
| : never | ||
| : never | ||
| : never; | ||
|
|
||
| // A literal like `'b'` extends the index signature's `string` key, so | ||
| // routing both through the same fragments misclassifies the literals. | ||
| type _RenameOnce<BaseType extends object, RenameMap> = Simplify< | ||
| & PickIndexSignature<BaseType> | ||
| & _RenameLiteralKeys<OmitIndexSignature<BaseType>, RenameMap> | ||
| >; | ||
|
|
||
| // TS's key-remapping inherits the first source's modifiers on collision, | ||
| // not "any" or "all". The four fragments specify the modifiers per target. | ||
| type _RenameLiteralKeys<BaseType extends object, RenameMap> = | ||
| // Readonly and required | ||
| & { | ||
| readonly [Key in keyof BaseType as _RouteTarget< | ||
| _TargetOf<Key, RenameMap>, | ||
| _ReadonlyTargets<BaseType, RenameMap>, | ||
| _RequiredTargets<BaseType, RenameMap>, | ||
| true, true | ||
| >]-?: _NewValue<BaseType, Key>; | ||
| } | ||
| // Readonly and optional | ||
| & { | ||
| readonly [Key in keyof BaseType as _RouteTarget< | ||
| _TargetOf<Key, RenameMap>, | ||
| _ReadonlyTargets<BaseType, RenameMap>, | ||
| _RequiredTargets<BaseType, RenameMap>, | ||
| true, false | ||
| >]?: _NewValue<BaseType, Key>; | ||
| } | ||
| // Mutable and required | ||
| & { | ||
| [Key in keyof BaseType as _RouteTarget< | ||
| _TargetOf<Key, RenameMap>, | ||
| _ReadonlyTargets<BaseType, RenameMap>, | ||
| _RequiredTargets<BaseType, RenameMap>, | ||
| false, true | ||
| >]-?: _NewValue<BaseType, Key>; | ||
| } | ||
| // Mutable and optional | ||
| & { | ||
| [Key in keyof BaseType as _RouteTarget< | ||
| _TargetOf<Key, RenameMap>, | ||
| _ReadonlyTargets<BaseType, RenameMap>, | ||
| _RequiredTargets<BaseType, RenameMap>, | ||
| false, false | ||
| >]?: _NewValue<BaseType, Key>; | ||
| }; | ||
|
|
||
| export {}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| import {expectType} from 'tsd'; | ||
| import type {RenameKeys} from '../source/rename-keys.d.ts'; | ||
|
|
||
| // Basic batch rename. | ||
| expectType<{id: string; first_name: string; created_at: Date}>( | ||
| {} as RenameKeys<{id: string; firstName: string; createdAt: Date}, {firstName: 'first_name'; createdAt: 'created_at'}>, | ||
| ); | ||
|
|
||
| // Empty rename map is identity. | ||
| expectType<{a: number; b: string}>({} as RenameKeys<{a: number; b: string}, {}>); | ||
|
|
||
| // Partial rename, unlisted keys are unchanged. | ||
| expectType<{alpha: number; b: string; c: boolean}>( | ||
| {} as RenameKeys<{a: number; b: string; c: boolean}, {a: 'alpha'}>, | ||
| ); | ||
|
|
||
| // `readonly` and optional modifiers are both applied to the new name. | ||
| expectType<{readonly identifier: string; name?: string; count: number}>( | ||
| {} as RenameKeys<{readonly id: string; label?: string; count: number}, {id: 'identifier'; label: 'name'}>, | ||
| ); | ||
|
|
||
| // Distributes over a union of rename maps. | ||
| expectType<{x: 1; b: 2} | {a: 1; y: 2}>( | ||
| {} as RenameKeys<{a: 1; b: 2}, {a: 'x'} | {b: 'y'}>, | ||
| ); | ||
|
|
||
| // Distributes over a union source type. | ||
| expectType<{kind: 'click'; element: string} | {kind: 'submit'; element: HTMLFormElement}>( | ||
| {} as RenameKeys<{kind: 'click'; target: string} | {kind: 'submit'; target: HTMLFormElement}, {target: 'element'}>, | ||
| ); | ||
|
|
||
| // Symbol target key. | ||
| declare const symbolKey: unique symbol; | ||
| type SymbolKey = typeof symbolKey; | ||
| expectType<{[symbolKey]: string; other: number}>( | ||
| {} as RenameKeys<{tag: string; other: number}, {tag: SymbolKey}>, | ||
| ); | ||
|
|
||
| // Number target keys. | ||
| expectType<{0: number; 1: string}>( | ||
| {} as RenameKeys<{first: number; second: string}, {first: 0; second: 1}>, | ||
| ); | ||
|
|
||
| // A literal target onto a string-indexed object is allowed. The index signature | ||
| // does not preclude adding a named property. | ||
| expectType<{[x: string]: number; b: 1}>( | ||
| {} as RenameKeys<{[x: string]: number; a: 1}, {a: 'b'}>, | ||
| ); | ||
|
|
||
| // Swapping two keys is allowed. Both keys rename away simultaneously, so no | ||
| // kept-key collision occurs. | ||
| expectType<{b: 1; a: 2}>({} as RenameKeys<{a: 1; b: 2}, {a: 'b'; b: 'a'}>); | ||
|
|
||
| // Renaming a key to itself is a no-op. | ||
| expectType<{a: 1; b: 2}>({} as RenameKeys<{a: 1; b: 2}, {a: 'a'}>); | ||
|
|
||
| // Typo'd source key is ignored, matching `Omit`'s result on missing keys. | ||
| expectType<{a: 1; b: 2}>({} as RenameKeys<{a: 1; b: 2}, {nme: 'fullName'}>); | ||
|
|
||
| // Optional rename-map entries have the optional modifier ignored. | ||
| expectType<{alpha: number; b: string}>({} as RenameKeys<{a: number; b: string}, {a?: 'alpha'}>); | ||
|
|
||
| // Collision with a kept property merges the values into a union. | ||
| expectType<{b: number | string}>({} as RenameKeys<{a: number; b: string}, {a: 'b'}>); | ||
|
|
||
| // Cross-union collision merges per union member. | ||
| expectType<{b: number} | {b: string}>({} as RenameKeys<{a: number} | {b: string}, {a: 'b'}>); | ||
|
|
||
| // Duplicate targets across the same rename map merge into a union. | ||
| expectType<{x: 1 | 2; c: 3}>({} as RenameKeys<{a: 1; b: 2; c: 3}, {a: 'x'; b: 'x'}>); | ||
|
|
||
| // Non-literal targets return `never`. A `string`-typed target would widen to | ||
| // an index signature. | ||
| expectType<never>({} as RenameKeys<{a: number; b: string}, {a: string}>); | ||
|
materwelonDhruv marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Union targets distribute, producing one output key per member. | ||
| expectType<{b: string; c: string}>({} as RenameKeys<{a: string}, {a: 'b' | 'c'}>); | ||
|
|
||
| // Union target preserves modifiers across all expanded keys. | ||
| expectType<{readonly b: string; readonly c: string}>( | ||
| {} as RenameKeys<{readonly a: string}, {a: 'b' | 'c'}>, | ||
| ); | ||
|
|
||
| // Preserves optional modifier only when all contributors are optional. | ||
| expectType<{b?: string; c?: string}>({} as RenameKeys<{a?: string}, {a: 'b' | 'c'}>); | ||
|
|
||
| // Union target combined with a kept-key collision. Both `b` and `c` are | ||
| // produced, and `b` merges the source's `a` and `b` values. | ||
| expectType<{b: 1 | 2; c: 1}>({} as RenameKeys<{a: 1; b: 2}, {a: 'b' | 'c'}>); | ||
|
|
||
| // Union target combined with another source mapping to the same target. | ||
| expectType<{b: string | number; c: number}>( | ||
| {} as RenameKeys<{a: string; d: number}, {a: 'b'; d: 'b' | 'c'}>, | ||
| ); | ||
|
|
||
| // Three-member union of rename maps distributes correctly. | ||
| expectType<{x: 1; b: 2; c: 3} | {a: 1; y: 2; c: 3} | {a: 1; b: 2; z: 3}>( | ||
| {} as RenameKeys<{a: 1; b: 2; c: 3}, {a: 'x'} | {b: 'y'} | {c: 'z'}>, | ||
| ); | ||
|
|
||
| // `any` source returns `never`. The target key cannot be proven absent from | ||
| // an `any` shape. | ||
| expectType<never>({} as RenameKeys<any, {a: 'x'}>); | ||
|
materwelonDhruv marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Generic instantiation. The constraint is structural-only, so the type can | ||
| // be used inside other generics without erroring at the definition site. | ||
| type WrappedGeneric<T, K extends keyof T & string> = RenameKeys<T, {[P in K]: `new_${P}`}>; | ||
|
materwelonDhruv marked this conversation as resolved.
Outdated
|
||
| expectType<{new_a: number; b: string; new_c: string}>({} as WrappedGeneric<{a: number; b: string; c: string}, 'a' | 'c'>); | ||
|
|
||
| // All contributors required. | ||
| expectType<{new_p: string | number | bigint}>( | ||
| {} as RenameKeys<{p1: string; p2: number; p3: bigint}, {p1: 'new_p'; p2: 'new_p'; p3: 'new_p'}>, | ||
| ); | ||
|
|
||
| // All contributors optional, optional modifier applies to the target. | ||
| expectType<{new_p?: string | number | bigint}>( | ||
| {} as RenameKeys<{p1?: string; p2?: number; p3?: bigint}, {p1: 'new_p'; p2: 'new_p'; p3: 'new_p'}>, | ||
| ); | ||
|
|
||
| // Mixed-optionality merge. The target is required because at least one | ||
| // contributor is required. The value type follows `exactOptionalPropertyTypes`. | ||
| // With EOPT on (as in this test project), the value omits `undefined`. | ||
| expectType<{new_p: string | number | bigint}>( | ||
| {} as RenameKeys<{p1: string; p2?: number; p3: bigint}, {p1: 'new_p'; p2: 'new_p'; p3: 'new_p'}>, | ||
| ); | ||
|
|
||
| // Mixed-readonly merge. The target is readonly because at least one | ||
| // contributor is readonly. | ||
| expectType<{readonly new_p: string | number | bigint}>( | ||
| {} as RenameKeys<{p1: string; readonly p2: number; p3: bigint}, {p1: 'new_p'; p2: 'new_p'; p3: 'new_p'}>, | ||
| ); | ||
|
|
||
| // Optional source first, required source second. The target is required | ||
| // because a required contributor exists, regardless of source order. | ||
| expectType<{x: number | string}>( | ||
| {} as RenameKeys<{a?: number; b: string}, {a: 'x'; b: 'x'}>, | ||
| ); | ||
|
|
||
| // Required source first, optional source second. | ||
| expectType<{x: string | number}>( | ||
| {} as RenameKeys<{a: string; b?: number}, {a: 'x'; b: 'x'}>, | ||
| ); | ||
|
|
||
| // Three sources with the optional one in the middle. | ||
| expectType<{z: number | string | bigint}>( | ||
| {} as RenameKeys<{a: number; b?: string; c: bigint}, {a: 'z'; b: 'z'; c: 'z'}>, | ||
| ); | ||
|
|
||
| // Three sources with the optional one at the end. | ||
| expectType<{z: number | string | bigint}>( | ||
| {} as RenameKeys<{a: number; b: string; c?: bigint}, {a: 'z'; b: 'z'; c: 'z'}>, | ||
| ); | ||
|
|
||
| // Mixed readonly AND mixed optionality. Any readonly contributor results in | ||
| // readonly, any required contributor results in required. | ||
| expectType<{readonly x: string | number}>( | ||
| {} as RenameKeys<{readonly a?: string; b: number}, {a: 'x'; b: 'x'}>, | ||
| ); | ||
|
|
||
| // Any readonly contributor with all optional contributors. | ||
| expectType<{readonly x?: string | number}>( | ||
| {} as RenameKeys<{readonly a?: string; b?: number}, {a: 'x'; b: 'x'}>, | ||
| ); | ||
|
|
||
| // Union target with mixed optionality across members. The required target | ||
| // is required, the optional-only target is optional. | ||
| expectType<{x: number | string; y?: number}>( | ||
| {} as RenameKeys<{a?: number; b: string}, {a: 'x' | 'y'; b: 'x'}>, | ||
| ); | ||
|
|
||
| // Union target where one member collides with a kept required key. | ||
| expectType<{b: number | string; c: number | boolean}>( | ||
| {} as RenameKeys<{a?: number; b: string; c: boolean}, {a: 'b' | 'c'}>, | ||
| ); | ||
|
|
||
| // Sources span all four modifier categories simultaneously. | ||
| expectType<{ | ||
| readonly x: 'a-val' | 'b-val'; | ||
| readonly y?: 'b-val' | 'c-val'; | ||
| z: 'd-val'; | ||
| }>( | ||
| {} as RenameKeys< | ||
| { | ||
| readonly a: 'a-val'; | ||
| b?: 'b-val'; | ||
| readonly c?: 'c-val'; | ||
| d: 'd-val'; | ||
| }, | ||
| {a: 'x'; b: 'x' | 'y'; c: 'y'; d: 'z'} | ||
| >, | ||
| ); | ||
|
|
||
| // Index signature is preserved when the only renamed source is optional. The | ||
| // index sig key must not affect the target's modifier routing. | ||
| expectType<{[x: string]: number; b?: 1}>( | ||
| {} as RenameKeys<{[x: string]: number; a?: 1}, {a: 'b'}>, | ||
| ); | ||
|
|
||
| // Three-way swap with the optional source in the middle. | ||
| expectType<{b: 1; c?: 2; a: 3}>( | ||
| {} as RenameKeys<{a: 1; b?: 2; c: 3}, {a: 'b'; b: 'c'; c: 'a'}>, | ||
| ); | ||
|
materwelonDhruv marked this conversation as resolved.
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.