-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16259-to-primitive.ts
89 lines (83 loc) · 1.76 KB
/
16259-to-primitive.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* 16259 - ToPrimitive
*
* Convert a property of type literal (label type) to a primitive type.
*
* For example
*
* ```typescript
* type X = {
* name: 'Tom',
* age: 30,
* married: false,
* addr: {
* home: '123456',
* phone: '13111111111'
* }
* }
*
* type Expected = {
* name: string,
* age: number,
* married: boolean,
* addr: {
* home: string,
* phone: string
* }
* }
* type Todo = ToPrimitive<X> // should be same as `Expected`
* ```
*
*
*/
/* _____________ Your Code Here _____________ */
type ToPrimitive<T> = T extends string
? string
: T extends number
? number
: T extends boolean
? boolean
: T extends Function
? Function
: T extends unknown[]
? T extends [infer A, ...infer R]
? [ToPrimitive<A>, ...ToPrimitive<R>]
: []
: T extends ReadonlyArray<unknown>
? T extends [infer A, ...infer R]
? readonly [ToPrimitive<A>, ...ToPrimitive<R>]
: readonly [ToPrimitive<T[0]>]
: T extends Record<string, unknown>
? {
[K in keyof T]: ToPrimitive<T[K]>
}
: T;
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type PersonInfo = {
name: 'Tom'
age: 30
married: false
addr: {
home: '123456'
phone: '13111111111'
}
hobbies: ['sing', 'dance']
readonlyArr: readonly ['test']
fn: () => any
}
type ExpectedResult = {
name: string
age: number
married: boolean
addr: {
home: string
phone: string
}
hobbies: [string, string]
readonlyArr: readonly [string]
fn: Function
}
type cases = [
Expect<Equal<ToPrimitive<PersonInfo>, ExpectedResult>>,
]