-
Notifications
You must be signed in to change notification settings - Fork 2
/
10_mapped-types-keyof.ts
59 lines (51 loc) · 1.17 KB
/
10_mapped-types-keyof.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
type Point = { x: number; y: number }
type P = keyof Point
type Arrayish = { [n: number]: unknown }
type A = keyof Arrayish
type Mapish = { [k: string]: boolean }
type M = keyof Mapish
// JS object keys are coerced to strings -> object["42"] is same as object[42]
type Same<T> = { [P in keyof T]: T[P] }
type ReadOnly<T> = { readonly [P in keyof T]: T[P] }
type Optional<T> = { [P in keyof T]?: T[P] }
type Nullable<T> = { [P in keyof T]: T[P] | null }
type Undefinedable<T> = { [P in keyof T]: T[P] | undefined }
interface User {
id: UserID
name: string
address: {
street: string
city: string
country: string
}
}
const user: Optional<User> = {
id: "1",
address: {
street: "Main Street",
city: "London",
country: "UK",
},
}
const user2: Undefinedable<User> = {
id: "1",
name: undefined,
address: {
street: "Main Street",
city: "London",
country: "UK",
},
}
user2.name = "John"
const user3: ReadOnly<Undefinedable<User>> = {
id: "1",
name: undefined,
address: {
street: "Main Street",
city: "London",
country: "UK",
},
}
function getProperty2<Type, Key extends keyof Type>(obj: Type, key: Key) {
return obj[key]
}