-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2757-partialbykeys.ts
58 lines (50 loc) · 1.53 KB
/
2757-partialbykeys.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* 2757 - PartialByKeys
*
* 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
*
* ```typescript
* interface User {
* name: string
* age: number
* address: string
* }
*
* type UserPartialName = PartialByKeys<User, 'name'> // { name?:string; age:number; address:string }
* ```
*/
/* _____________ Your Code Here _____________ */
type PartialByKeysV1<T extends object, K extends keyof T = keyof T> =
(Omit<T, K> & { [Key in K]?: T[Key] }) extends infer Intersection
? { [Key in keyof Intersection]: Intersection[Key] }
: never;
type PartialByKeys<T extends object, K extends keyof T = keyof T> =
Omit<(Omit<T, K> & { [Key in K]?: T[Key] }), never>
/* _____________ 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>>,
]