Definite assignment
- TypeScript course
- Advanced
- Lesson 46/57
- 4 min
Learn initialization with definite assignment.
Definite assignment
When a class property is declared but not assigned in the constructor, TypeScript errors. The ! mark makes a definite assignment assertion: ! is placed after the property name and tells TypeScript "this property will be assigned later".
class Config {
host!: string; // definite assignment assertion
load() {
this.host = "localhost";
}
}Constructor vs definite assignment
Assigning a property in the constructor is the safest approach; TypeScript checks all properties are assigned. However, in some cases (e.g. ORM or framework loading) assignment happens later; then ! is used for definite assignment assertion.
class User {
name: string; // assigned in constructor
constructor(name: string) {
this.name = name;
}
}
class Entity {
id!: number; // will be assigned by framework
save() {
console.log(this.id);
}
}Practice Config class with definite assignment
Define a Config class: with host!: string and port!: number properties (with definite assignment). Write a load() method: assign this.host = "localhost" and this.port = 8080. Create a Config instance, call load(), 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öntemiyle host ve port ata
// Config örneği oluştur, load çağır, sonuçları yazdırSample solution
class Config {
host!: string;
port!: number;
load(): void {
this.host = "localhost";
this.port = 8080;
}
}
const c = new Config();
c.load();
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 does the ! mark on a class property indicate?
- The property is optional
- The property is private
- The property is readonly
- The property will be assigned later Correct answer
Explanation: The ! mark after a property name makes a definite assignment assertion; TypeScript trusts that this property will be assigned later outside the constructor.
2 definite assignment assertion
class Config {
host____: string;
load() {
this.host = "localhost";
}
}
class Config {
host!: string;
load() {
this.host = "localhost";
}
}
Explanation: The ! mark is placed after the property name and makes a definite assignment assertion; it tells TypeScript the property will be assigned later.
3 Definite assignment parts
| Term | Meaning |
|---|---|
host!: string |
definite assignment assertion |
constructor'da atama |
safest approach |
framework yüklemesi |
! for later assignment |
! işareti |
after property name |