[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}

 

PropertyKeyis 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
  }>>,
]

 

posted @   Zhentiw  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示