2757 - PartialByKeys
原创2025/4/30大约 1 分钟
2757 - PartialByKeys
by jiangshan (@jiangshanmeta) #中等 #object
题目
实现一个通用的PartialByKeys<T, K>
,它接收两个类型参数T
和K
。
K
指定应设置为可选的T
的属性集。当没有提供K
时,它就和普通的Partial<T>
一样使所有属性都是可选的。
例如:
interface User {
name: string
age: number
address: string
}
type UserPartialName = PartialByKeys<User, 'name'> // { name?:string; age:number; address:string }
在 Github 上查看:https://tsch.js.org/2757/zh-CN
代码
/* _____________ 你的代码 _____________ */
type PartialByKeys<T, K extends keyof T = keyof T> = Omit<{
[P in K]+?: T[P]
} & {
[P in Exclude<keyof T, K>]: T[P]
}, never>
type A = { name: string }
type B = { age: number }
type C = { address: string }
type D = Omit<A & B & C, never>
// type D = {
// name: string;
// age: number;
// address: string;
// }
// type Omit<T, K extends keyof any> = { [P in Exclude<keyof T, K>]: T[P]; }
测试用例
/* _____________ 测试用例 _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
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>>,
]
相关链接
分享你的解答:https://tsch.js.org/2757/answer/zh-CN
查看解答:https://tsch.js.org/2757/solutions
更多题目:https://tsch.js.org/zh-CN