[Typescript] 36. Medium - Merge
Merge two types into a new type. Keys of the second type overrides keys of the first type.
For example
type foo = {
name: string;
age: string;
}
type coo = {
age: number;
sex: string
}
type Result = Merge<foo,coo>; // expected to be {name: string, age: number, sex: string}
PropertyKey
is the special key for Record
type: https://www.typescriptlang.org/docs/handbook/2/mapped-types.html/* _____________ Your Code Here _____________ */
type Merge<F extends Record<PropertyKey, any>, S extends Record<PropertyKey, any>> = {
[K in keyof F | keyof S]: K extends keyof S ? S[K] : F[K]
}
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type Foo = {
a: number
b: string
}
type Bar = {
b: number
c: boolean
}
type cases = [
Expect<Equal<Merge<Foo, Bar>, {
a: number
b: number
c: boolean
}>>,
]
Without PropertyKey
:
/* _____________ Your Code Here _____________ */
type Merge<F, S> = {
[K in keyof F | keyof S]: K extends keyof S ? S[K] : K extends keyof F ? F[K]: never
}
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type Foo = {
a: number
b: string
}
type Bar = {
b: number
c: boolean
}
type cases = [
Expect<Equal<Merge<Foo, Bar>, {
a: number
b: number
c: boolean
}>>,
]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-09-25 [Machine Learning] Learning Curves
2017-09-25 [Javascript AST] 2. Introduction: Write a simple ESLint rule
2016-09-25 [Angular2 Router] Style the Active Angular 2 Navigation Element with routerLinkActive
2016-09-25 [Angular2 Router] Lazy Load Angular 2 Modules with the Router
2016-09-25 [Angular2 Router] Build Angular 2 Navigation with routerLink
2016-09-25 [Angular 2 Router] Configure Your First Angular 2 Route