strictPropertyInitialization
strictPropertyInitialization là compiler option bắt buộc khởi tạo class property.
- Mặc định:
truenếu strict được bật, ngược lại làfalse - Phiên bản thêm vào: 2.7
- TypeScript khuyến nghị nên bật
Để option này có hiệu lực, cần set strictNullChecks thành true.
Giải thích
Đặt strictPropertyInitialization thành true để cảnh báo các class property chưa được khởi tạo giá trị.
tsclassFoo {Property 'prop' has no initializer and is not definitely assigned in the constructor.2564Property 'prop' has no initializer and is not definitely assigned in the constructor.: number; prop }
tsclassFoo {Property 'prop' has no initializer and is not definitely assigned in the constructor.2564Property 'prop' has no initializer and is not definitely assigned in the constructor.: number; prop }
Khởi tạo phải được thực hiện bằng một trong các cách sau:
- Khởi tạo trong constructor
- Khởi tạo bằng initializer
- Type annotate bằng union type với undefined
Dưới đây là ví dụ khởi tạo trong constructor:
tsclassFoo {prop : number;constructor() {this.prop = 1;}}
tsclassFoo {prop : number;constructor() {this.prop = 1;}}
Dưới đây là ví dụ khởi tạo bằng initializer:
tsclassFoo {prop : number = 1;// ^^^initializer}
tsclassFoo {prop : number = 1;// ^^^initializer}
Khi type của property là union type với undefined, không cảnh báo ngay cả khi không khởi tạo:
tsclassFoo {prop : number | undefined;}
tsclassFoo {prop : number | undefined;}
Khi property là optional cũng không cảnh báo:
tsclassFoo {prop ?: number;}
tsclassFoo {prop ?: number;}
Chia sẻ kiến thức
strictPropertyInitialization của TypeScript là compiler option bắt buộc khởi tạo property.
⚠️strictNullChecks cũng cần set thành true
✅Bắt buộc khởi tạo trong constructor HOẶC initializer
🙆🏻♂️Type annotate bằng union type với undefined là OK
Từ 『Survival TypeScript』
Thông tin liên quan
📄️ strict
Bật hàng loạt các option thuộc nhóm strict
📄️ Field
Để instance có field trong JavaScript, gán giá trị cho property của object đã instance hóa.