Optional property của object type
Trong TypeScript, để type cho optional property của object, thêm ? sau tên property.
tstypeSize = {width ?: number;};
tstypeSize = {width ?: number;};
Có thể gán object không có optional property cho object type có optional property.
tsconstsize :Size = {}; // OK
tsconstsize :Size = {}; // OK
Cũng có thể gán object có giá trị optional property là undefined.
tsconstsize :Size = {width :undefined ,}; // OK
tsconstsize :Size = {width :undefined ,}; // OK
Tuy nhiên, không thể gán nếu giá trị optional property là null.
tsconstsize :Size = {Type 'null' is not assignable to type 'number | undefined'.2322Type 'null' is not assignable to type 'number | undefined'.: null, width };
tsconstsize :Size = {Type 'null' is not assignable to type 'number | undefined'.2322Type 'null' is not assignable to type 'number | undefined'.: null, width };
Nhưng nếu tắt strictNullChecks, có thể gán null.
Khi strictNullChecks là falsetsconstsize :Size = {width : null,};
Khi strictNullChecks là falsetsconstsize :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