Nhảy tới nội dung

strictPropertyInitialization

strictPropertyInitialization là compiler option bắt buộc khởi tạo class property.

  • Mặc định: true nế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
cẩn thận

Để 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ị.

ts
class Foo {
prop: number;
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.
}
ts
class Foo {
prop: number;
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.
}

Khởi tạo phải được thực hiện bằng một trong các cách sau:

  1. Khởi tạo trong constructor
  2. Khởi tạo bằng initializer
  3. Type annotate bằng union type với undefined

Dưới đây là ví dụ khởi tạo trong constructor:

ts
class Foo {
prop: number;
 
constructor() {
this.prop = 1;
}
}
ts
class Foo {
prop: number;
 
constructor() {
this.prop = 1;
}
}

Dưới đây là ví dụ khởi tạo bằng initializer:

ts
class Foo {
prop: number = 1;
// ^^^initializer
}
ts
class Foo {
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:

ts
class Foo {
prop: number | undefined;
}
ts
class Foo {
prop: number | undefined;
}

Khi property là optional cũng không cảnh báo:

ts
class Foo {
prop?: number;
}
ts
class Foo {
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』

Đăng nội dung này lên X

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.