-
-
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 17 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,191 @@ | ||
| 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 {ReadonlyKeysOf} from './readonly-keys-of.d.ts'; | ||
| import type {RequiredKeysOf} from './required-keys-of.d.ts'; | ||
| import type {OptionalKeysOf} from './optional-keys-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 // Once per member when BaseType is a union. | ||
| ? BaseType extends object | ||
| ? RenameMap extends RenameMap // Once per member when the rename map is a union. | ||
| ? _AllTargetsAreLiterals<Required<RenameMap>> extends true | ||
| ? _RenameOnce<BaseType, Required<RenameMap>> | ||
| : never | ||
| : never | ||
| : never | ||
| : never; | ||
|
|
||
| // True only when every new name in the map is a literal such as 'a' or 1. The | ||
| // brackets compare the whole union at once, so one wide target (like string, | ||
| // which would turn into an index signature) makes the result false. | ||
| type _AllTargetsAreLiterals<RenameMap> = [ | ||
| { | ||
| [Key in keyof RenameMap]: IsLiteral<RenameMap[Key]>; | ||
| }[keyof RenameMap], | ||
| ] extends [true] | ||
| ? true | ||
| : false; | ||
|
|
||
| // The new name for a source key. A key missing from the map keeps its own name. | ||
| type _TargetOf<SourceKey, RenameMap> = | ||
| SourceKey extends keyof RenameMap | ||
| ? RenameMap[SourceKey] extends PropertyKey | ||
| ? RenameMap[SourceKey] | ||
| : SourceKey | ||
| : SourceKey; | ||
|
|
||
| // The value type for one renamed key. With exactOptionalPropertyTypes on, an | ||
| // optional key's value should not carry undefined, so Required strips it. With the | ||
| // flag off, BaseType[Key] keeps the undefined an optional key may hold. | ||
| type _NewValue<BaseType, Key extends keyof BaseType> = | ||
| IsExactOptionalPropertyTypesEnabled extends true | ||
| ? Required<Pick<BaseType, Key>>[Key] | ||
| : BaseType[Key]; | ||
|
|
||
| type _ReadonlyTargets<BaseType extends object, RenameMap> = _TargetOf<ReadonlyKeysOf<BaseType>, RenameMap>; | ||
| type _RequiredTargets<BaseType extends object, RenameMap> = _TargetOf<RequiredKeysOf<BaseType>, RenameMap>; | ||
| type _OptionalTargets<BaseType extends object, RenameMap> = _TargetOf<OptionalKeysOf<BaseType>, RenameMap>; | ||
|
|
||
| // Keeps a new name only when its readonly and required state matches the block | ||
| // being built. `Target extends Target` runs this once per name when the new name | ||
| // is a union. | ||
| 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; | ||
|
|
||
| // Handle the index signature on its own. A literal key like `'b'` counts as a | ||
| // match for an index signature's `string` key, so renaming them together would | ||
| // mix the two up. PickIndexSignature carries the index signature across | ||
| // unchanged, and the named keys go through the rename. | ||
| type _RenameOnce<BaseType extends object, RenameMap> = Simplify< | ||
| & PickIndexSignature<BaseType> | ||
| & _RenameLiteralKeys<OmitIndexSignature<BaseType>, RenameMap> | ||
| >; | ||
|
|
||
| // Rename the named keys, then restore any undefined the required blocks dropped. | ||
| // The second argument is the set of new names fed by both a required and an | ||
| // optional source key. | ||
| type _RenameLiteralKeys<BaseType extends object, RenameMap> = | ||
| _RestoreMergedUndefined< | ||
| _RouteToBlocks<BaseType, RenameMap>, | ||
| _RequiredTargets<BaseType, RenameMap> & _OptionalTargets<BaseType, RenameMap> | ||
| >; | ||
|
|
||
| // A new name fed by both a required and an optional source key becomes one | ||
| // required key, and the required block's `-?` strips the undefined the optional | ||
| // key allowed. With exactOptionalPropertyTypes off that undefined should stay, so add | ||
| // it back on those names. With the flag on there is nothing to restore. | ||
| type _RestoreMergedUndefined<Result, MixedTargets> = | ||
| IsExactOptionalPropertyTypesEnabled extends true | ||
| ? Result | ||
| : { | ||
| [Key in keyof Result]: Key extends MixedTargets | ||
| ? Result[Key] | undefined | ||
| : Result[Key]; | ||
| }; | ||
|
|
||
| // Build the renamed keys in four blocks, one for each pairing of readonly or | ||
| // mutable with required or optional. When several source keys collide on one new | ||
| // name, TS's key remapping would copy only the first key's readonly and optional | ||
| // flags, so each block sets its own flags and _RouteTarget sends every name to | ||
| // the block that matches. | ||
| type _RouteToBlocks<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 {}; |
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.