Cơ BảnTypeScript iconTypeScript

Optional properties (?) và readonly properties là gì?

Optional property (prop?: Type) có thể có hoặc không, type là Type | undefined khi access.

Khác với prop: Type | undefined — cái sau vẫn yêu cầu key có mặt khi tạo object. readonly property không thể reassign sau khởi tạo (chỉ compile time). Readonly<T> làm tất cả properties readonly.

typescript
interface User {
  id: number;
  nickname?: string;          // caller có thể bỏ qua
  bio: string | undefined;    // caller phải cung cấp key, nhưng value có thể undefined
  readonly createdAt: Date;   // không thể reassign
}

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript