如果你要宽容别人的过错,就要把眼光放到自己身上。——佚名

题目:

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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/*

Intro:

PowerUsers idea was bad. Once those users got
extended permissions, they started bullying others
and we lost a lot of great users.
As a response we spent all the remaining money
on the marketing and got even more users.
We need to start preparing to move everything to a
real database. For now we just do some mocks.

The server API format was decided to be the following:

In case of success: { status: 'success', data: RESPONSE_DATA }
In case of error: { status: 'error', error: ERROR_MESSAGE }

The API engineer started creating types for this API and
quickly figured out that the amount of types needed to be
created is too big.

Exercise:

Remove UsersApiResponse and AdminsApiResponse types
and use generic type ApiResponse in order to specify API
response formats for each of the functions.

*/

interface User {
type: 'user';
name: string;
age: number;
occupation: string;
}

interface Admin {
type: 'admin';
name: string;
age: number;
role: string;
}

type Person = User | Admin;

const admins: Admin[] = [
{ type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
{ type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' }
];

const users: User[] = [
{ type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
{ type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' }
];

export type ApiResponse<T> = unknown;

type AdminsApiResponse = (
{
status: 'success';
data: Admin[];
} |
{
status: 'error';
error: string;
}
);

export function requestAdmins(callback: (response: AdminsApiResponse) => void) {
callback({
status: 'success',
data: admins
});
}

type UsersApiResponse = (
{
status: 'success';
data: User[];
} |
{
status: 'error';
error: string;
}
);

export function requestUsers(callback: (response: UsersApiResponse) => void) {
callback({
status: 'success',
data: users
});
}

export function requestCurrentServerTime(callback: (response: unknown) => void) {
callback({
status: 'success',
data: Date.now()
});
}

export function requestCoffeeMachineQueueLength(callback: (response: unknown) => void) {
callback({
status: 'error',
error: 'Numeric value has exceeded Number.MAX_SAFE_INTEGER.'
});
}

function logPerson(person: Person) {
console.log(
` - ${person.name}, ${person.age}, ${person.type === 'admin' ? person.role : person.occupation}`
);
}

function startTheApp(callback: (error: Error | null) => void) {
requestAdmins((adminsResponse) => {
console.log('Admins:');
if (adminsResponse.status === 'success') {
adminsResponse.data.forEach(logPerson);
} else {
return callback(new Error(adminsResponse.error));
}

console.log();

requestUsers((usersResponse) => {
console.log('Users:');
if (usersResponse.status === 'success') {
usersResponse.data.forEach(logPerson);
} else {
return callback(new Error(usersResponse.error));
}

console.log();

requestCurrentServerTime((serverTimeResponse) => {
console.log('Server time:');
if (serverTimeResponse.status === 'success') {
console.log(` ${new Date(serverTimeResponse.data).toLocaleString()}`);
} else {
return callback(new Error(serverTimeResponse.error));
}

console.log();

requestCoffeeMachineQueueLength((coffeeMachineQueueLengthResponse) => {
console.log('Coffee machine queue length:');
if (coffeeMachineQueueLengthResponse.status === 'success') {
console.log(` ${coffeeMachineQueueLengthResponse.data}`);
} else {
return callback(new Error(coffeeMachineQueueLengthResponse.error));
}

callback(null);
});
});
});
});
}

startTheApp((e: Error | null) => {
console.log();
if (e) {
console.log(`Error: "${e.message}", but it's fine, sometimes errors are inevitable.`)
} else {
console.log('Success!');
}
});

// In case you are stuck:
// https://www.typescriptlang.org/docs/handbook/2/generics.html

报错:

1
2
3
4
5
6
7
8
9
index.ts(137,21): error TS2571: Object is of type 'unknown'.
index.ts(138,48): error TS2571: Object is of type 'unknown'.
index.ts(140,47): error TS2571: Object is of type 'unknown'.
index.ts(147,25): error TS2571: Object is of type 'unknown'.
index.ts(148,43): error TS2571: Object is of type 'unknown'.
index.ts(150,51): error TS2571: Object is of type 'unknown'.
test.ts(35,5): error TS2344: Type 'false' does not satisfy the constraint 'true'.
test.ts(88,5): error TS2344: Type 'false' does not satisfy the constraint 'true'.
test.ts(105,5): error TS2344: Type 'false' does not satisfy the constraint 'true'.

答案:

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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/*

Intro:

PowerUsers idea was bad. Once those users got
extended permissions, they started bullying others
and we lost a lot of great users.
As a response we spent all the remaining money
on the marketing and got even more users.
We need to start preparing to move everything to a
real database. For now we just do some mocks.

The server API format was decided to be the following:

In case of success: { status: 'success', data: RESPONSE_DATA }
In case of error: { status: 'error', error: ERROR_MESSAGE }

The API engineer started creating types for this API and
quickly figured out that the amount of types needed to be
created is too big.

Exercise:

Remove UsersApiResponse and AdminsApiResponse types
and use generic type ApiResponse in order to specify API
response formats for each of the functions.

*/

interface User {
type: 'user';
name: string;
age: number;
occupation: string;
}

interface Admin {
type: 'admin';
name: string;
age: number;
role: string;
}

type Person = User | Admin;

const admins: Admin[] = [
{ type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
{ type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' }
];

const users: User[] = [
{ type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
{ type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' }
];

export type ApiResponse<T> = {
status: 'success';
data: T;
} | {
status: 'error';
error: string;
};

export function requestAdmins(callback: (response: ApiResponse<Admin[]>) => void) {
callback({
status: 'success',
data: admins
});
}

export function requestUsers(callback: (response: ApiResponse<User[]>) => void) {
callback({
status: 'success',
data: users
});
}

export function requestCurrentServerTime(callback: (response: ApiResponse<number>) => void) {
callback({
status: 'success',
data: Date.now()
});
}

export function requestCoffeeMachineQueueLength(callback: (response: ApiResponse<number>) => void) {
callback({
status: 'error',
error: 'Numeric value has exceeded Number.MAX_SAFE_INTEGER.'
});
}

function logPerson(person: Person) {
console.log(
` - ${person.name}, ${person.age}, ${person.type === 'admin' ? person.role : person.occupation}`
);
}

function startTheApp(callback: (error: Error | null) => void) {
requestAdmins((adminsResponse) => {
console.log('Admins:');
if (adminsResponse.status === 'success') {
adminsResponse.data.forEach(logPerson);
} else {
return callback(new Error(adminsResponse.error));
}

console.log();

requestUsers((usersResponse) => {
console.log('Users:');
if (usersResponse.status === 'success') {
usersResponse.data.forEach(logPerson);
} else {
return callback(new Error(usersResponse.error));
}

console.log();

requestCurrentServerTime((serverTimeResponse) => {
console.log('Server time:');
if (serverTimeResponse.status === 'success') {
console.log(` ${new Date(serverTimeResponse.data).toLocaleString()}`);
} else {
return callback(new Error(serverTimeResponse.error));
}

console.log();

requestCoffeeMachineQueueLength((coffeeMachineQueueLengthResponse) => {
console.log('Coffee machine queue length:');
if (coffeeMachineQueueLengthResponse.status === 'success') {
console.log(` ${coffeeMachineQueueLengthResponse.data}`);
} else {
return callback(new Error(coffeeMachineQueueLengthResponse.error));
}

callback(null);
});
});
});
});
}

startTheApp((e: Error | null) => {
console.log();
if (e) {
console.log(`Error: "${e.message}", but it's fine, sometimes errors are inevitable.`)
} else {
console.log('Success!');
}
});

// In case you are stuck:
// https://www.typescriptlang.org/docs/handbook/2/generics.html