Required<T>
Required<T> là utility type loại bỏ ? (nghĩa là optional) khỏi tất cả các property của T.
Type argument của Required<T>
T
Type argument T nhận kiểu biểu diễn object type.
Ví dụ sử dụng Required
tstypePerson = {surname : string;middleName ?: string;givenName : string;};typeRequiredPerson =Required <Person >;
tstypePerson = {surname : string;middleName ?: string;givenName : string;};typeRequiredPerson =Required <Person >;
RequiredPerson ở trên sẽ giống với kiểu sau:
tstypeRequiredPerson = {surname : string;middleName : string;givenName : string;};
tstypeRequiredPerson = {surname : string;middleName : string;givenName : string;};
Implementation của Required
Required<T> được implement như sau:
tstypeRequired <T > = {[P in keyofT ]-?:T [P ];};
tstypeRequired <T > = {[P in keyofT ]-?:T [P ];};
So sánh với Partial<T> sẽ thấy sự khác biệt:
tstypePartial <T > = {[P in keyofT ]?:T [P ];};
tstypePartial <T > = {[P in keyofT ]?:T [P ];};
Phần khác nhau là -? và ?. ? là optional modifier, làm cho property trở thành optional. -? có nghĩa là loại bỏ optional modifier. Do đó, Required<T> tạo ra kiểu với ? (nghĩa là optional) bị loại bỏ khỏi tất cả các property của T.
Dấu - này được gọi là mapping modifier.
Thông tin liên quan
📄️ Partial<T>
Biến tất cả property thành optional
📄️ Mapped Types
Với index type, bạn có thể tự do thiết lập bất kỳ key nào khi gán giá trị, nhưng khi truy cập phải kiểm tra undefined mỗi lần. Nếu format input đã được xác định rõ ràng, bạn có thể cân nhắc sử dụng Mapped Types.