[Typescript] 98. Medium - Append to object

Implement a type that adds a new field to the interface. The type takes the three arguments. The output should be an object with the new field.

For example

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

 

/* _____________ Your Code Here _____________ */
type Merge<T extends Record<PropertyKey, any>> = {
  [Key in keyof T]: T[Key]
} 
type AppendToObject<T extends Record<PropertyKey, any>, U extends string | number | symbol, V extends any> = Merge<T & {
  [Key in U]: V  
}>

/* _____________ Test Cases _____________ */
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
  isMotherRussia: false | undefined
}

type cases = [
  Expect<Equal<AppendToObject<test1, 'home', boolean>, testExpect1>>,
  Expect<Equal<AppendToObject<test2, 'home', 1>, testExpect2>>,
  Expect<Equal<AppendToObject<test3, 'isMotherRussia', false | undefined>, testExpect3>>,
]

 

posted @   Zhentiw  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-11-12 [Javascript] Broadcaster + Operator + Listener pattern -- 17. Building a Word Matching Game
2019-11-12 [Go] Slices vs Array
2015-11-12 [AngularJS] ng-if vs ng-show
2015-11-12 [ES6] Array.find()
2015-11-12 [ES6] Array.findIndex()
2015-11-12 [Javascript] Object.assign()
2014-11-12 [Unit Testing for Zombie] 06. Using Factory
点击右上角即可分享
微信分享提示