1. Welcome and Icebreaker:
- If you could make any property in your life optional, required, or readonly, what would you choose?
2. Outline the Session:
- We’ll learn about the built-in utility types
Partial, Required, and Readonly in TypeScript.
- Learning Outcomes: Understand how to use these utility types to transform object types.
- Let’s make our types more flexible!
3. Concept Explanation:
Partial<T>: Makes all properties of T optional.
Required<T>: Makes all properties of T required.
Readonly<T>: Makes all properties of T readonly (cannot be reassigned).
- These are mapped types provided by TypeScript for common transformations.
- Syntax:
type PartialUser = Partial<User>;
type RequiredUser = Required<User>;
type ReadonlyUser = Readonly<User>;
4. Live Coding Demonstration:
type User = { id: number; name: string; email?: string };
const partial: Partial<User> = { name: "Alice" };
const required: Required<User> = { id: 1, name: "Bob", email: "bob@example.com" };
const readonlyUser: Readonly<User> = { id: 2, name: "Carol" };
// readonlyUser.id = 3; // Error: Cannot assign to 'id' because it is a read-only property.
5. Tasks:
- Short Exercise:
- Create a type
Book and use Partial<Book>, Required<Book>, and Readonly<Book>.
- Try to assign only some properties to a
Partial<Book>.
- Try to modify a property of a
Readonly<Book> and observe the error.