We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
题目链接:AppendToObject,答题
实现 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; };
将 T 中 key 和泛型 K 变成联合类型,然后就可以通过遍历 key 得到新对象
T
key
K
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> >;
方法二和方法三是相同的思路,把两个对象变成交叉对象,然后再将交叉对象转变成普通对象
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目
题目链接:AppendToObject,答题
实现
AppendToObject
,往对象中添加一个属性答案
方法一
知识点
将
T
中key
和泛型K
变成联合类型,然后就可以通过遍历key
得到新对象方法二
方法三
知识点
方法二和方法三是相同的思路,把两个对象变成交叉对象,然后再将交叉对象转变成普通对象
The text was updated successfully, but these errors were encountered: