-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnonNullAssertions.ts
43 lines (34 loc) · 958 Bytes
/
nonNullAssertions.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
type BoringType = {
a: number,
b: number
}
let boringVar: BoringType;
function initializeTheBoringVar() {
boringVar = {
a: 1,
b: 2
}
}
initializeTheBoringVar();
// Below will raise an error as boringVar used before the initialization.
// console.log(boringVar.a);
// console.log(boringVar.b);
// We want compiler to trust us with !:
console.log('Believe me it is initalised', boringVar!.a, boringVar!.b);
type EmailCanBeMissing = {
name: string,
email?: string | null | undefined
}
function ensureEmailExists(ecbm: EmailCanBeMissing) {
if (!ecbm.email) {
throw new Error('Email is missing...')
}
}
function sendEmail(email: string) {
console.log('Sent!');
}
function ensureEmailExistsAndSendEmail(ecbm: EmailCanBeMissing) {
ensureEmailExists(ecbm);
// sendEmail(ecbm.email); // this will cause a compile time error
sendEmail(ecbm.email!); // !: Trust me, I checked the email.
}