Skip to content

PartialByKeys

约 328 字大约 1 分钟

2022-12-01

题目

Github: PartialByKeys

实现一个通用的 PartialByKeys<T, K> ,它接收两个类型参数 TK

K 指定应设置为可选的T的属性集。当没有提供 K 时,它就和普通的 Partial<T> 一样使所有属性都是可选的。

interface User {
  name: string
  age: number
  address: string
}

type UserPartialName = PartialByKeys<User, 'name'>
// { name?:string; age:number; address:string }

解题思路

略。

答案

type PartialByKeys<T, K extends keyof T = keyof T> = Omit<{
  [P in keyof T as P extends K ? P : never]?: T[P]
} & {
  [P in keyof T as P extends K ? never : P]: T[P]
}, never>

验证

interface User {
  
name
: string
age
: number
address
: string
} interface UserPartialName {
name
?: string
age
: number
address
: string
} interface UserPartialNameAndAge {
name
?: string
age
?: number
address
: string
} type
cases
= [
Expect
<
Equal
<
PartialByKeys
<User, 'name'>, UserPartialName>>,
Expect
<
Equal
<
PartialByKeys
<User, 'name' | 'age'>, UserPartialNameAndAge>>,
Expect
<
Equal
<
PartialByKeys
<User>,
Partial
<User>>>,
// @ts-expect-error
Expect
<
Equal
<
PartialByKeys
<User, 'name' | 'unknown'>, UserPartialName>>,
]

参考