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

32. AppendToObject #41

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

32. AppendToObject #41

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

Comments

@astak16
Copy link
Owner

astak16 commented Jul 19, 2022

题目

题目链接:AppendToObject答题

实现 AppendToObject,往对象中添加一个属性

import type { Equal, Expect } from "@type-challenges/utils";

type test1 = {
  key: "cat";
  value: "green";
};

type testExpect1 = {
  key: "cat";
  value: "green";
  home: boolean;
};

type test2 = {
  key: "dog" | undefined;
  value: "white";
  sun: true;
};

type testExpect2 = {
  key: "dog" | undefined;
  value: "white";
  sun: true;
  home: 1;
};

type test3 = {
  key: "cow";
  value: "yellow";
  sun: false;
};

type testExpect3 = {
  key: "cow";
  value: "yellow";
  sun: false;
  isMotherRussia: false | undefined;
};

type cases = [
  Expect<Equal<AppendToObject<test1, "home", boolean>, testExpect1>>,
  Expect<Equal<AppendToObject<test2, "home", 1>, testExpect2>>,
  Expect<
    Equal<
      AppendToObject<test3, "isMotherRussia", false | undefined>,
      testExpect3
    >
  >
];

答案

方法一

type AppendToObject<T, K extends keyof any, V> = {
  [key in keyof T | K]: key extends keyof T ? T[key] : V;
};

知识点

Tkey 和泛型 K 变成联合类型,然后就可以通过遍历 key 得到新对象

方法二

type IntersectionToObject<T> = { [K in keyof T]: T[K] };
type AppendToObject<T, K extends keyof any, V> = IntersectionToObject<
  T & {
    [key in K]: V;
  }
>;

方法三

type IntersectionToObject<T> = { [K in keyof T]: T[K] };
type AppendToObject<T, K extends keyof any, V> = IntersectionToObject<
  T & Record<K, V>
>;

知识点

方法二和方法三是相同的思路,把两个对象变成交叉对象,然后再将交叉对象转变成普通对象

@astak16 astak16 added the medium label Jul 19, 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