Summary - Strict null
- TypeScript course
- Advanced
- Lesson 48/57
- 4 min
Write a safe configuration loader with strict null.
Summary - Strict null
Strict null, definite assignment, and non-null assertion together form a safe configuration loader. strictNullChecks catches null values; definite assignment uses ! for late-starting assignments; non-null assertion narrows with ! where the value is known not to be null.
class Config {
host!: string;
port!: number;
load(env: { HOST: string | null; PORT: string | null }): void {
this.host = env.HOST!;
this.port = Number(env.PORT!);
}
}Practice Write a configuration loader
Define a Config class: with host!: string and port!: number definite assignment properties. Write a load(env: { HOST: string | null; PORT: string | null }): void method: assign this.host = env.HOST! and this.port = Number(env.PORT!). Create a Config instance, call c.load({ HOST: "localhost", PORT: "8080" }), then print results via console.log(c.host) and console.log(c.port).
Starter code
// Config sınıfını tanımla (host ve port definite assignment ile)
// load yöntemi yaz (env parametresiyle, non-null assertion kullan)
// Config örneği oluştur, load çağır, sonuçları yazdırSample solution
class Config {
host!: string;
port!: number;
load(env: { HOST: string | null; PORT: string | null }): void {
this.host = env.HOST!;
this.port = Number(env.PORT!);
}
}
const c = new Config();
c.load({ HOST: "localhost", PORT: "8080" });
console.log(c.host);
console.log(c.port);Expected output
localhost 8080
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between definite assignment (!) and non-null assertion (!)?
- Non-null assertion performs a runtime check
- They are the same
- Definite assignment is used in property declaration, non-null assertion in expression Correct answer
- Definite assignment is used only in classes
Explanation: Definite assignment uses ! in a class property declaration to say the property will be assigned later; non-null assertion uses ! after an expression to assert the value is not null.
2 Assign Config host
class Config {
host!: string;
port!: number;
load(env: { HOST: string | null; PORT: string | null }): void {
this.host = ____;
this.port = Number(env.PORT!);
}
}
class Config {
host!: string;
port!: number;
load(env: { HOST: string | null; PORT: string | null }): void {
this.host = env.HOST!;
this.port = Number(env.PORT!);
}
}
Explanation: The env.HOST! expression makes a non-null assertion; HOST may be null but the assertion narrows it to string so it can be assigned to the host property.
3 Strict null summary matching
| Term | Meaning |
|---|---|
strictNullChecks |
separates null and undefined from other types |
definite assignment (!) |
in property declaration |
non-null assertion (!) |
in expression |
akış analizi |
narrowing in if condition |