feat(typescript-types): Add Assign<Shape,Defaults,Obj>
This commit is contained in:
@@ -27,3 +27,11 @@ The types included in this library are categorized by their purpose.
|
||||
| [`OptionalKeysOf<T>`][] | A union of all keys of `T` that are marked as optional. If `T` is a union, a union of the optional keys of all union members of `T` is returned. |
|
||||
|
||||
[`OptionalKeysOf<T>`]: src/optional-keys-of.ts
|
||||
|
||||
#### Combination Types
|
||||
|
||||
| Type | Description |
|
||||
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
||||
| [`Assign<Shape, Defaults, Obj>`][] | Return a type with the structure of `Shape` and value types from `Obj` or `Default` for missing optional keys in `Obj`. |
|
||||
|
||||
[`Assign<Shape, Defaults, Obj>`]: src/assign.ts
|
||||
|
||||
9
packages/typescript-types/src/assign.ts
Normal file
9
packages/typescript-types/src/assign.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { OptionalKeysOf } from './optional-keys-of.js'
|
||||
|
||||
export type Assign<
|
||||
Shape extends object,
|
||||
Defaults extends Pick<Required<Shape>, OptionalKeysOf<Shape>>,
|
||||
Obj extends Shape
|
||||
> = {
|
||||
[K in keyof Shape]: K extends keyof Obj ? Obj[K] : K extends keyof Defaults ? Defaults[K] : never
|
||||
}
|
||||
29
packages/typescript-types/test/assign.tst.ts
Normal file
29
packages/typescript-types/test/assign.tst.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { Assign } from '@/assign.js'
|
||||
import { expect } from 'tstyche'
|
||||
|
||||
interface Person {
|
||||
name: string
|
||||
age?: number
|
||||
}
|
||||
|
||||
interface Options extends Person {
|
||||
relations?: Array<Person>
|
||||
}
|
||||
|
||||
interface DefaultValues {
|
||||
name: 'Max Mustermann'
|
||||
age: 17
|
||||
relations: []
|
||||
}
|
||||
|
||||
expect<Assign<Options, DefaultValues, { name: 'Another Name' }>>().type.toBe<{
|
||||
name: 'Another Name'
|
||||
age?: 17
|
||||
relations?: []
|
||||
}>()
|
||||
|
||||
expect<Assign<Options, DefaultValues, { name: 'Another Name'; age: 18 }>>().type.toBe<{
|
||||
name: 'Another Name'
|
||||
age?: 18
|
||||
relations?: []
|
||||
}>()
|
||||
Reference in New Issue
Block a user