首页 > 其他分享 >[Typescript] 36. Medium - Merge

[Typescript] 36. Medium - Merge

时间:2022-09-25 03:22:23浏览次数:69  
标签:Typescript string _____________ 36 number Merge keyof type

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

 

标签:Typescript,string,_____________,36,number,Merge,keyof,type
From: https://www.cnblogs.com/Answer1215/p/16727144.html

相关文章