[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>>,
]
分类:
TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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