[Typescript] 49. Medium - PartialByKeys
typescript Medium 49
2023-09-14 08:59:11 时间
Implement a generic PartialByKeys<T, K>
which takes two type argument T
and K
.
K
specify the set of properties of T
that should set to be optional. When K
is not provided, it should make all properties optional just like the normal Partial<T>
.
For example
interface User {
name: string
age: number
address: string
}
type UserPartialName = PartialByKeys<User, 'name'> // { name?:string; age:number; address:string }
/* _____________ Your Code Here _____________ */
type MergeObject<T> = { [P in keyof T]: T[P] };
type PartialByKeys<T, K extends keyof T = keyof T> = MergeObject<
Omit<T, K> & {
[P in keyof T as P extends K ? P : never]?: T[P];
}>;
/* _____________ Test Cases _____________ */
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>>,
]
相关文章
- typescript web_typescript在线运行
- Typescript: Getting Started
- Typescript: Access window object with type check
- 【TypeScript】中的数组和元组之间的关系
- TypeScript基础知识
- 快速搭建基于Vue3+Vite2+Arco+Typescript+Pinia后台管理系统模板,文末有福利
- 解决 Typescript 文件被识别为视频的问题
- 【编码规范】Typescript 编码风格指南
- 初识 TypeScript
- TypeScript | 笔记
- Laravel + Vue 3(Vite、TypeScript)SPA 设置
- 调查:React 仍然是使用最广泛的前端框架,TypeScript 是优先选项
- 开心档之TypeScript 变量声明