rimo030 / type-challenges

Collection of TypeScript type challenges with online judge
https://tsch.js.org/
MIT License
2 stars 0 forks source link

no - 527 Append to object #94

Open rimo030 opened 3 months ago

rimo030 commented 3 months ago
type AppendToObject<T, U extends string, V> = Omit<T & { [K in U] : V}, never>
import type { Equal, Expect } from '@type-challenges/utils'

type test1 = {
  key: 'cat'
  value: 'green'
}

type testExpect1 = {
  key: 'cat'
  value: 'green'
  home: boolean
}

type test2 = {
  key: 'dog' | undefined
  value: 'white'
  sun: true
}

type testExpect2 = {
  key: 'dog' | undefined
  value: 'white'
  sun: true
  home: 1
}

type test3 = {
  key: 'cow'
  value: 'yellow'
  sun: false
}

type testExpect3 = {
  key: 'cow'
  value: 'yellow'
  sun: false
  moon: false | undefined
}

type cases = [
  Expect<Equal<AppendToObject<test1, 'home', boolean>, testExpect1>>,
  Expect<Equal<AppendToObject<test2, 'home', 1>, testExpect2>>,
  Expect<Equal<AppendToObject<test3, 'moon', false | undefined>, testExpect3>>,
]
rimo030 commented 3 months ago

처음에는 인터섹션을 풀기위해 mapper를 따로 두었는데, Omit<T, never>를 이용하는 방법도 있다는 것을 배웠다.

type Mapped<T> = { [K in keyof T] : T[K] }

type AppendToObject<T, U extends string, V> = Mapped<T & { [K in U] : V}>