Append to object
介绍
实现一个为接口添加一个新字段的类型。该类型接收三个参数,返回带有新字段的接口类型。
ts
type Test = { id: '1' }type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }
View on GitHubts
type Test = { id: '1' }type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }
起点
ts
/* _____________ Your Code Here _____________ */typeAppendToObject <T ,U ,V > = any/* _____________ Test Cases _____________ */typetest1 = {key : 'cat'value : 'green'}typetestExpect1 = {key : 'cat'value : 'green'home : boolean}typetest2 = {key : 'dog' | undefinedvalue : 'white'sun : true}typetestExpect2 = {key : 'dog' | undefinedvalue : 'white'sun : truehome : 1}typetest3 = {key : 'cow'value : 'yellow'sun : false}typetestExpect3 = {key : 'cow'value : 'yellow'sun : falsemoon : false | undefined}typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <AppendToObject <test1 , 'home', boolean>,testExpect1 >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <AppendToObject <test2 , 'home', 1>,testExpect2 >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <AppendToObject <test3 , 'moon', false | undefined>,testExpect3 >>,]
take the challengets
/* _____________ Your Code Here _____________ */typeAppendToObject <T ,U ,V > = any/* _____________ Test Cases _____________ */typetest1 = {key : 'cat'value : 'green'}typetestExpect1 = {key : 'cat'value : 'green'home : boolean}typetest2 = {key : 'dog' | undefinedvalue : 'white'sun : true}typetestExpect2 = {key : 'dog' | undefinedvalue : 'white'sun : truehome : 1}typetest3 = {key : 'cow'value : 'yellow'sun : false}typetestExpect3 = {key : 'cow'value : 'yellow'sun : falsemoon : false | undefined}typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <AppendToObject <test1 , 'home', boolean>,testExpect1 >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <AppendToObject <test2 , 'home', 1>,testExpect2 >>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <AppendToObject <test3 , 'moon', false | undefined>,testExpect3 >>,]
解决方案
Spoiler warning // Click to reveal answer
ts
typeAppendToObject <T ,U extends string,V > =T extends {[index : string]: any}? {[K in keyofT |U ]:K extends keyofT ?T [K ] :V }:T ;
ts
typeAppendToObject <T ,U extends string,V > =T extends {[index : string]: any}? {[K in keyofT |U ]:K extends keyofT ?T [K ] :V }:T ;
ts
// most populartypeAppendToObject <T ,U extends keyof any,V > = {[K in keyofT |U ]:K extends keyofT ?T [K ] :V ;};
ts
// most populartypeAppendToObject <T ,U extends keyof any,V > = {[K in keyofT |U ]:K extends keyofT ?T [K ] :V ;};