[TypeScript] Type Challenges #527 - Append to object

68 阅读1分钟

题目描述

实现一个为接口添加一个新字段的类型。该类型接收三个参数,返回带有新字段的接口类型。

例如:

type Test = { id: '1' }
type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }

题解

// ============= Test Cases =============
import type { Equal, Expect } from './test-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>>,
]


// ============= Your Code Here =============
type AppendToObject<T, U extends PropertyKey, V> = {
  [P in keyof T | U]: P extends keyof T ? T[P] : V
}

类型约束

通过U extends PropertyKeyU进行约束,确保U是合法的键类型

遍历联合类型

[P in keyof T | U]:遍历T的所有键和新键U的联合类型

条件赋值

P extends keyof T ? T[P] : V

  • 如果PT的键,保留T[P]的值
  • 如果P是新键U,将值设置为V