Nhảy tới nội dung

Optional property của object type

Trong TypeScript, để type cho optional property của object, thêm ? sau tên property.

ts
type Size = {
width?: number;
};
ts
type Size = {
width?: number;
};

Có thể gán object không có optional property cho object type có optional property.

ts
const size: Size = {}; // OK
ts
const size: Size = {}; // OK

Cũng có thể gán object có giá trị optional property là undefined.

ts
const size: Size = {
width: undefined,
}; // OK
ts
const size: Size = {
width: undefined,
}; // OK

Tuy nhiên, không thể gán nếu giá trị optional property là null.

ts
const size: Size = {
width: null,
Type 'null' is not assignable to type 'number | undefined'.2322Type 'null' is not assignable to type 'number | undefined'.
};
ts
const size: Size = {
width: null,
Type 'null' is not assignable to type 'number | undefined'.2322Type 'null' is not assignable to type 'number | undefined'.
};

Nhưng nếu tắt strictNullChecks, có thể gán null.

Khi strictNullChecks là false
ts
const size: Size = {
width: null,
};
Khi strictNullChecks là false
ts
const size: Size = {
width: null,
};

Thông tin liên quan

📄️ Optional chaining

Optional chaining ?. trong JavaScript là cách an toàn để tham chiếu property mà không gây error ngay cả khi object reference là null hoặc undefined.

📄️ strictNullChecks

Làm nghiêm ngặt check null và undefined