跳到主要内容

Merge

介绍

将两个类型合并成一个类型,第二个类型的键会覆盖第一个类型的键。

ts
ts
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type Merge<F, S> = any
 
/* _____________ Test Cases _____________ */
 
type Foo = {
a: number
b: string
}
type Bar = {
b: number
c: boolean
}
 
type cases = [
Expect<Equal<Merge<Foo, Bar>, {
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
a: number
b: number
c: boolean
}>>,
]
 
ts
/* _____________ Your Code Here _____________ */
 
type Merge<F, S> = any
 
/* _____________ Test Cases _____________ */
 
type Foo = {
a: number
b: string
}
type Bar = {
b: number
c: boolean
}
 
type cases = [
Expect<Equal<Merge<Foo, Bar>, {
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
a: number
b: number
c: boolean
}>>,
]
 
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type Merge<F, S> = {
[K in keyof F | keyof S]: K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}
ts
type Merge<F, S> = {
[K in keyof F | keyof S]: K extends keyof S ? S[K] : K extends keyof F ? 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
*/
 
 
type Merge<F, S> = {
[K in keyof F | keyof S]: K extends keyof S ? S[K] : F[K]
Type 'K' cannot be used to index type 'F'.2536Type 'K' cannot be used to index type 'F'.
}
 
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
*/
 
 
type Merge<F, S> = {
[K in keyof F | keyof S]: K extends keyof S ? S[K] : F[K]
Type 'K' cannot be used to index type 'F'.2536Type 'K' cannot be used to index type 'F'.
}
 
view more solutions