Skip to content
Open
Show file tree
Hide file tree
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 May 28, 2026
80c9aec
feat: add `RenameKeys` type
materwelonDhruv May 28, 2026
0eddd05
fix(lint): lint error in import statement
materwelonDhruv May 28, 2026
229c206
fix: reject key collisions and optional map entries in `RenameKey`/`R…
materwelonDhruv May 29, 2026
9c3e2d3
tests: cover `RenameKey`/`RenameKeys` edge cases and rejections
materwelonDhruv May 29, 2026
889d438
fix: linter needs enable statements after file-level disable statements
materwelonDhruv May 29, 2026
a407f21
fix: various issues
materwelonDhruv May 31, 2026
92b4a86
chore: update readme
materwelonDhruv May 31, 2026
6bf4632
fix: lint issues
materwelonDhruv May 31, 2026
d556969
feat: add reliable merging behavior
materwelonDhruv Jun 22, 2026
c90f79b
chore: remove `RenameKey` type
materwelonDhruv Jun 22, 2026
4f71ea3
refactor: use the existing internal type for this
materwelonDhruv Jun 22, 2026
c4a9851
refactor: make option keys no-op instead of fail
materwelonDhruv Jun 22, 2026
8da94ac
refactor: allow unions distributing their types on rename
materwelonDhruv Jun 22, 2026
c09e705
fix: correct modifier handling on merged targets
materwelonDhruv Jun 23, 2026
bbba36a
fix: unsynced readme desc
materwelonDhruv Jun 23, 2026
231568a
fix: incorrect optional behavior with EOPT off
materwelonDhruv Jun 26, 2026
3b6b979
fix: make non-literal targets no op instead of produce a `never`
materwelonDhruv Jun 26, 2026
438f46f
refactor: simplify the type's impl + some more tests
materwelonDhruv Jul 9, 2026
8615b9b
Merge remote-tracking branch 'upstream/main' into add-rename-key
materwelonDhruv Jul 9, 2026
aafd4ea
fix: updated API
materwelonDhruv Jul 9, 2026
2b3db9a
refactor: the source value type is not needed anymore
materwelonDhruv Jul 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ export type {KeyAsString} from './source/key-as-string.d.ts';
export type {Exact} from './source/exact.d.ts';
export type {ReadonlyTuple} from './source/readonly-tuple.d.ts';
export type {OverrideProperties} from './source/override-properties.d.ts';
export type {RenameKey} from './source/rename-key.d.ts';
export type {RenameKeys} from './source/rename-keys.d.ts';
export type {OptionalKeysOf} from './source/optional-keys-of.d.ts';
export type {IsOptionalKeyOf} from './source/is-optional-key-of.d.ts';
export type {HasOptionalKeys} from './source/has-optional-keys.d.ts';
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ Click the type names for complete docs.
- [`MergeDeep`](source/merge-deep.d.ts) - Merge two objects or two arrays/tuples recursively into a new type.
- [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys.
- [`OverrideProperties`](source/override-properties.d.ts) - Override existing properties of the given type. Similar to `Merge`, but enforces that the original type has the properties you want to override.
- [`RenameKey`](source/rename-key.d.ts) - Rename a single key in an object type, preserving its value type and modifiers (optional, readonly). Other keys pass through unchanged.
- [`RenameKeys`](source/rename-keys.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.
- [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys, while keeping the remaining keys as is.
- [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly one of the given keys and disallows more, while keeping the remaining keys as is.
- [`RequireAllOrNone`](source/require-all-or-none.d.ts) - Create a type that requires all of the given keys or none of the given keys, while keeping the remaining keys as is.
Expand Down
60 changes: 60 additions & 0 deletions source/rename-key.d.ts
Comment thread
materwelonDhruv marked this conversation as resolved.
Outdated
Comment thread
materwelonDhruv marked this conversation as resolved.
Outdated
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 {};
131 changes: 131 additions & 0 deletions source/rename-keys.d.ts
Comment thread
materwelonDhruv marked this conversation as resolved.
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;
Comment thread
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 {};
103 changes: 103 additions & 0 deletions test-d/rename-key.ts
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'>;
Loading