• [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
      }>>,
    ]
  • 相关阅读:
    重塑矩阵
    数组拆分
    最大连续1的个数
    石子游戏
    概率与期望知识总结
    洛谷 P3951 NOIP 2017 小凯的疑惑
    关于结构体的初始化
    山海经:线段树维护最大子段和
    偏序 分块+bitset
    分块练习C. interval
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16727144.html
Copyright © 2020-2023  润新知