Merge
介绍
将两个类型合并成一个类型,第二个类型的键会覆盖第一个类型的键。
ts
View on GitHubts
起点
ts
/* _____________ Your Code Here _____________ */typeMerge <F ,S > = any/* _____________ Test Cases _____________ */typeFoo = {a : numberb : string}typeBar = {b : numberc : boolean}typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Merge <Foo ,Bar >, {a : numberb : numberc : boolean}>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeMerge <F ,S > = any/* _____________ Test Cases _____________ */typeFoo = {a : numberb : string}typeBar = {b : numberc : boolean}typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Merge <Foo ,Bar >, {a : numberb : numberc : boolean}>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
typeMerge <F ,S > = {[K in keyofF | keyofS ]:K extends keyofS ?S [K ] :K extends keyofF ?F [K ] : never;}
ts
typeMerge <F ,S > = {[K in keyofF | keyofS ]:K extends keyofS ?S [K ] :K extends keyofF ?F [K ] : never;}
ts
// 注意, 为什么不能使用如下形式呢?/*** 会产生如下报错: Type 'K' cannot be used to index type 'F'.ts(2536)* 看意思是, F cannot guarantee that K is a valid key for F* why? 应该是TS无法自动缩减narrow K的类型到keyof F*/typeMerge <F ,S > = {[Type 'K' cannot be used to index type 'F'.2536Type 'K' cannot be used to index type 'F'.K in keyofF | keyofS ]:K extends keyofS ?S [K ] :F [K ]}
ts
// 注意, 为什么不能使用如下形式呢?/*** 会产生如下报错: Type 'K' cannot be used to index type 'F'.ts(2536)* 看意思是, F cannot guarantee that K is a valid key for F* why? 应该是TS无法自动缩减narrow K的类型到keyof F*/typeMerge <F ,S > = {[Type 'K' cannot be used to index type 'F'.2536Type 'K' cannot be used to index type 'F'.K in keyofF | keyofS ]:K extends keyofS ?S [K ] :F [K ]}