Sobes.tech
Middle+

Third part of the TypeScript task: create a new type based on the Delivery type, where all fields are optional (can have the value undefined) and cannot change their value (readonly). Use utility types Partial and Readonly.

sobes.tech AI

Answer from AI

In TypeScript, you can create a new type that makes all fields of the original type Delivery optional and readonly by using utility types Partial and Readonly together:

type Delivery = {
  address: string;
  date: Date;
  cost: number;
};

// New type with optional and readonly fields
type ReadonlyPartialDelivery = Readonly<Partial<Delivery>>;

// Example usage
const delivery: ReadonlyPartialDelivery = {
  address: '123 Main St'
};
// delivery.address = '456 Other St'; // Error: cannot modify readonly field

Partial<T> makes all fields of type T optional, and Readonly<T> makes all fields readonly. Their combination allows creating a type with optional and immutable fields.

Third part of the TypeScript task: create a new type… - sobes.tech