feat(typescript-types): Add Assign<Shape,Defaults,Obj>

This commit is contained in:
T. R. Bernstein
2025-07-14 12:59:15 +02:00
parent 48076172bf
commit 610e7a0518
3 changed files with 46 additions and 0 deletions

View File

@@ -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

View 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
}

View 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?: []
}>()