Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

35. Merge #44

Open
astak16 opened this issue Jul 20, 2022 · 0 comments
Open

35. Merge #44

astak16 opened this issue Jul 20, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jul 20, 2022

题目

题目链接:Merge答题

实现 Merge 类型,将两个类型合并为一个新的类型,如果两个类型中有相同的 key,后一个类型的 key 覆盖前面一个类型的 key

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

答案

方法一

type Merge<T, U> = {
  [K in keyof T | keyof U]: K extends keyof U
    ? U[K]
    : K extends keyof T
    ? T[K]
    : never;
};

方法二

type Merge<T, U> = {
  [K in keyof (T & U)]: K extends keyof U
    ? U[K]
    : K extends keyof T
    ? T[K]
    : never;
};

方法三

type Merge<T, U> = Omit<Omit<T, keyof U> & U, never>;
@astak16 astak16 added the medium label Jul 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant