-
-
Notifications
You must be signed in to change notification settings - Fork 724
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 10 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
|
materwelonDhruv marked this conversation as resolved.
Outdated
|
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,60 @@ | ||
| import type {KeysOfUnion} from './keys-of-union.d.ts'; | ||
| import type {RenameKeys} from './rename-keys.d.ts'; | ||
|
|
||
| /** | ||
| Rename a single key in an object type, preserving its value type and modifiers (optional, readonly). Other keys pass through unchanged. | ||
|
|
||
| @example | ||
| ``` | ||
| import type {RenameKey} from 'type-fest'; | ||
|
|
||
| type User = { | ||
| id: string; | ||
| name: string; | ||
| createdAt: Date; | ||
| }; | ||
|
|
||
| type Renamed = RenameKey<User, 'createdAt', 'created_at'>; | ||
| //=> {id: string; name: string; created_at: Date} | ||
| ``` | ||
|
|
||
| Works with unions, distributing over each member: | ||
|
|
||
| @example | ||
| ``` | ||
| import type {RenameKey} from 'type-fest'; | ||
|
|
||
| type Event = | ||
| | {kind: 'click'; target: string} | ||
| | {kind: 'submit'; target: HTMLFormElement}; | ||
|
|
||
| type Renamed = RenameKey<Event, 'target', 'element'>; | ||
| //=> { | ||
| // kind: 'click'; | ||
| // element: string; | ||
| // } | { | ||
| // kind: 'submit'; | ||
| // element: HTMLFormElement; | ||
| // } | ||
| ``` | ||
|
|
||
| Returns `never` under the same conditions as `RenameKeys`. The wrapper also rejects a typo'd source key at the call site via `FromKey extends KeysOfUnion<BaseType>`: | ||
|
|
||
| @example | ||
| ``` | ||
| import type {RenameKey} from 'type-fest'; | ||
|
|
||
| // @ts-expect-error 'missing' is not a property of the source. | ||
| type Bad = RenameKey<{a: number}, 'missing', 'renamed'>; | ||
| ``` | ||
|
|
||
| @see {@link RenameKeys} | ||
| @category Object | ||
| */ | ||
| export type RenameKey< | ||
| BaseType, | ||
| FromKey extends KeysOfUnion<BaseType>, | ||
| ToKey extends PropertyKey, | ||
| > = RenameKeys<BaseType, {[Key in FromKey]: ToKey}>; | ||
|
|
||
| export {}; |
|
materwelonDhruv marked this conversation as resolved.
|
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,131 @@ | ||
| import type {IsLiteral} from './is-literal.d.ts'; | ||
| import type {IsUnion} from './is-union.d.ts'; | ||
| import type {IsAny} from './is-any.d.ts'; | ||
| import type {IsNever} from './is-never.d.ts'; | ||
| import type {HasOptionalKeys} from './has-optional-keys.d.ts'; | ||
| import type {IsReadonlyKeyOf} from './is-readonly-key-of.d.ts'; | ||
| import type {Simplify} from './simplify.d.ts'; | ||
|
|
||
| /** | ||
| Rename keys in an object type according to a map of old-to-new names. Keys absent from the map pass through unchanged. The value type, the optional modifier, and the readonly modifier go to the new key. | ||
|
|
||
| Distributes over a union of rename maps and over a union of source types. See {@link RenameKey} for the single-key form. | ||
|
|
||
| When multiple source keys end up at the same target, the target's value type is the union of the contributors' value types. The target keeps the optional modifier only when every contributor is optional, and is `readonly` when any contributor is `readonly`. With `exactOptionalPropertyTypes` disabled, mixed-optionality merges also union `undefined` into the value type. | ||
|
|
||
| A rename map entry whose key is not a property of the source type is ignored, matching the behavior of `Omit`. | ||
|
|
||
| Returns `never` if any of the following hold: | ||
| - A rename map entry is optional (e.g. `{a?: 'b'}`). | ||
| - A rename map entry's value is not a single literal `PropertyKey` (rejects unions like `'b' | 'c'` and 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} | ||
| ``` | ||
|
|
||
| @see {@link RenameKey} | ||
| @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. | ||
| ? HasOptionalKeys<RenameMap> extends true | ||
| ? never | ||
| : _AllTargetsAreSingleLiterals<RenameMap> extends true | ||
| ? _RenameOnce<BaseType, RenameMap> | ||
| : never | ||
| : never | ||
| : never | ||
| : never; | ||
|
|
||
| type _IsSingleLiteral<Target> = IsLiteral<Target> extends true | ||
| ? IsUnion<Target> extends true | ||
| ? false | ||
| : true | ||
| : false; | ||
|
|
||
| type _AllTargetsAreSingleLiterals<RenameMap> = [ | ||
| { | ||
| [Key in keyof RenameMap]: _IsSingleLiteral<RenameMap[Key]>; | ||
| }[keyof RenameMap], | ||
| ] extends [true] | ||
| ? true | ||
| : false; | ||
|
|
||
| // With EOPT off, the optional modifier implicitly admits `undefined`, so | ||
| // `{a: undefined}` is assignable to `{a?: string}`. With EOPT on it isn't. | ||
| type _IsExactOptionalDisabled = {a: undefined} extends {a?: string} ? true : false; | ||
|
materwelonDhruv marked this conversation as resolved.
Outdated
|
||
|
|
||
| type _TargetOf<SourceKey, RenameMap> = | ||
| SourceKey extends keyof RenameMap | ||
| ? RenameMap[SourceKey] extends PropertyKey | ||
| ? RenameMap[SourceKey] | ||
| : SourceKey | ||
| : SourceKey; | ||
|
|
||
| // `Required<Pick>` strips the optional-modifier-induced `undefined` so an | ||
| // optional source merging into a required target does not leak `undefined` | ||
| // into the value when EOPT is on. With EOPT off, the natural `BaseType[Key]` | ||
| // keeps `undefined` so mixed-optionality merges still admit it. | ||
| type _NewValue<BaseType, Key extends keyof BaseType> = | ||
| _IsExactOptionalDisabled extends true | ||
| ? BaseType[Key] | ||
| : Required<Pick<BaseType, Key>>[Key]; | ||
|
|
||
| // TS's mapped-type key-remapping picks the readonly modifier of the first | ||
| // source iterated, not "any". This collects the targets that need to be | ||
| // forced 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]; | ||
|
|
||
| type _RenameOnce<BaseType extends object, RenameMap> = Simplify< | ||
| & { | ||
| readonly [Key in keyof BaseType as _TargetOf<Key, RenameMap> extends _ReadonlyTargets<BaseType, RenameMap> | ||
| ? _TargetOf<Key, RenameMap> | ||
| : never]: _NewValue<BaseType, Key>; | ||
| } | ||
| & { | ||
| [Key in keyof BaseType as _TargetOf<Key, RenameMap> extends _ReadonlyTargets<BaseType, RenameMap> | ||
| ? never | ||
| : _TargetOf<Key, RenameMap>]: _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,103 @@ | ||
| import {expectType} from 'tsd'; | ||
| import type {RenameKey} from '../source/rename-key.d.ts'; | ||
|
|
||
| // Basic rename. | ||
| expectType<{id: string; name: string; created_at: Date}>( | ||
| {} as RenameKey<{id: string; name: string; createdAt: Date}, 'createdAt', 'created_at'>, | ||
| ); | ||
|
|
||
| // Single-key source. | ||
| expectType<{amount: number}>({} as RenameKey<{value: number}, 'value', 'amount'>); | ||
|
|
||
| // Preserves the optional modifier. | ||
| expectType<{id: string; name?: string}>( | ||
| {} as RenameKey<{id: string; label?: string}, 'label', 'name'>, | ||
| ); | ||
|
|
||
| // Preserves the readonly modifier. | ||
| expectType<{readonly identifier: string; name: string}>( | ||
| {} as RenameKey<{readonly id: string; name: string}, 'id', 'identifier'>, | ||
| ); | ||
|
|
||
| // `readonly` and optional combine and travel together to the new name. | ||
| expectType<{readonly b?: number; x: string}>( | ||
| {} as RenameKey<{readonly a?: number; x: string}, 'a', 'b'>, | ||
| ); | ||
|
|
||
| // An explicit `| undefined` value stays required; it does not become optional. | ||
| expectType<{b: string | undefined; x: number}>( | ||
| {} as RenameKey<{a: string | undefined; x: number}, 'a', 'b'>, | ||
| ); | ||
|
|
||
| // Renaming is shallow: a nested object value is preserved verbatim. | ||
| expectType<{b: {nested: number; deep: {x: string}}; c: boolean}>( | ||
| {} as RenameKey<{a: {nested: number; deep: {x: string}}; c: boolean}, 'a', 'b'>, | ||
| ); | ||
|
|
||
| // Symbol target key. | ||
| declare const symbolKey: unique symbol; | ||
| type SymbolKey = typeof symbolKey; | ||
| expectType<{[symbolKey]: string}>({} as RenameKey<{tag: string}, 'tag', SymbolKey>); | ||
|
|
||
| // Number target key. | ||
| expectType<{0: number}>({} as RenameKey<{first: number}, 'first', 0>); | ||
|
|
||
| // Symbol source key. | ||
| declare const tag: unique symbol; | ||
| type Tag = typeof tag; | ||
| expectType<{label: 'x'; name: string}>({} as RenameKey<{[tag]: 'x'; name: string}, Tag, 'label'>); | ||
|
|
||
| // Distributes over union members. | ||
| expectType<{kind: 'click'; element: string} | {kind: 'submit'; element: HTMLFormElement}>( | ||
| {} as RenameKey< | ||
| {kind: 'click'; target: string} | {kind: 'submit'; target: HTMLFormElement}, | ||
| 'target', | ||
| 'element' | ||
| >, | ||
| ); | ||
|
|
||
| // The source key need not exist in every union member. | ||
| expectType<{kind: 'a'; value: string} | {kind: 'b'}>( | ||
| {} as RenameKey<{kind: 'a'; payload: string} | {kind: 'b'}, 'payload', 'value'>, | ||
| ); | ||
|
|
||
| // Renaming a key to itself is a no-op. | ||
| expectType<{a: number; b: string}>({} as RenameKey<{a: number; b: string}, 'a', 'a'>); | ||
|
|
||
| // A literal target onto a string-indexed object is fine: the index signature | ||
| // does not preclude adding a named property. | ||
| expectType<{[x: string]: number; b: 1}>( | ||
| {} as RenameKey<{[x: string]: number; a: 1}, 'a', 'b'>, | ||
| ); | ||
|
|
||
| // Renaming onto an existing key merges the values into a union at the target. | ||
| expectType<{b: number | string}>({} as RenameKey<{a: number; b: string}, 'a', 'b'>); | ||
|
|
||
| // Cross-union collision merges per union member; the source key in a member | ||
| // that lacks it is ignored, the member that has it merges. | ||
| expectType<{b: number} | {b: string}>({} as RenameKey<{a: number} | {b: string}, 'a', 'b'>); | ||
|
|
||
| // Source must be a property of BaseType. | ||
| // @ts-expect-error 'missing' is not a property of the source. | ||
| type _Bad1 = RenameKey<{a: number}, 'missing', 'renamed'>; | ||
|
|
||
| // In a union source, the source key must exist in at least one member. | ||
| // @ts-expect-error 'b' is not a property of any union member. | ||
| type _Bad2 = RenameKey<{a: number} | {a: string}, 'b', 'c'>; | ||
|
|
||
| // `any` source returns `never`: the target key cannot be proven absent from | ||
| // an `any` shape. | ||
| expectType<never>({} as RenameKey<any, 'a', 'b'>); | ||
|
|
||
| // `never` source returns `never`. The wrapper constraint `KeysOfUnion<never>` | ||
| // evaluates to `string | number | symbol` (not `never`), so the call site does | ||
| // not error; the body short-circuits via the `IsNever<BaseType>` check. | ||
| expectType<never>({} as RenameKey<never, 'a', 'b'>); | ||
|
|
||
| // `unknown` source: no keys to rename. | ||
| // @ts-expect-error `unknown` has no keys. | ||
| type _Bad4 = RenameKey<unknown, 'a', 'b'>; | ||
|
|
||
| // Renaming is shallow; nested keys are not addressable. | ||
| // @ts-expect-error 'nested' is not a top-level key. | ||
| type _Bad5 = RenameKey<{a: {nested: number}}, 'nested', 'x'>; |
Oops, something went wrong.
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.