Skip to content

Commit

Permalink
Add SetFieldType type (#721)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
lucasteles and sindresorhus committed Oct 25, 2023
1 parent 017bf38 commit 964466c
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.d.ts
Expand Up @@ -101,6 +101,7 @@ export type {IsUnknown} from './source/is-unknown';
export type {IfUnknown} from './source/if-unknown';
export type {ArrayIndices} from './source/array-indices';
export type {ArrayValues} from './source/array-values';
export type {SetFieldType} from './source/set-field-type';

// Template literal types
export type {CamelCase} from './source/camel-case';
Expand Down
1 change: 1 addition & 0 deletions readme.md
Expand Up @@ -175,6 +175,7 @@ Click the type names for complete docs.
- [`IntRange`](source/int-range.d.ts) - Generate a union of numbers.
- [`ArrayIndices`](source/array-indices.d.ts) - Provides valid indices for a constant array or tuple.
- [`ArrayValues`](source/array-values.d.ts) - Provides all values for a constant array or tuple.
- [`SetFieldType`](source/set-field-type.d.ts) - Create a type that changes the type of the given keys.

### Type Guard

Expand Down
37 changes: 37 additions & 0 deletions source/set-field-type.d.ts
@@ -0,0 +1,37 @@
import type {Except} from './except';
import type {Simplify} from './simplify';

/**
Create a type that changes the type of the given keys.
Use-cases:
- Creating variations of a base model.
- Fixing incorrect external types.
@see `Merge` if you need to change multiple properties to different types.
@example
```
import type {SetFieldType} from 'type-fest';
type MyModel = {
id: number;
createdAt: Date;
updatedAt: Date;
};
type MyModelApi = SetFieldType<MyModel, 'createdAt' | 'updatedAt', string>;
// {
// id: number;
// createdAt: string;
// updatedAt: string;
// }
```
@category Object
*/
export type SetFieldType<BaseType, Keys extends keyof BaseType, NewType> =
Simplify<
Except<BaseType, Keys> &
Record<Keys, NewType>
>;
14 changes: 14 additions & 0 deletions test-d/set-field-type.ts
@@ -0,0 +1,14 @@
import {expectNotAssignable, expectType} from 'tsd';
import type {SetFieldType} from '../index';

declare const variation1: SetFieldType<{a: number}, 'a', string>;
expectType<{a: string}>(variation1);

declare const variation2: SetFieldType<{a: number; b: boolean; c: Date}, 'a' | 'b', string>;
expectType<{a: string; b: string; c: Date}>(variation2);

declare const variation3: SetFieldType<{a: string; b: boolean; c: Date}, 'b' | 'c', number>;
expectType<{a: string; b: number; c: number}>(variation3);

declare const variation4: SetFieldType<{a: string; b: string; c: string}, 'b', number>;
expectNotAssignable<{a: string; b: string; c: string}>(variation4);

0 comments on commit 964466c

Please sign in to comment.