Problem Statement
Create an object type with required and optional fields, then show safe updates.
Explanation
Use `?` to mark optionals and prefer immutable-style updates. Required properties must exist; optional properties may be omitted. Spreading into a new object preserves the original and allows the compiler to verify property names and types. With `exactOptionalPropertyTypes`, TypeScript distinguishes missing from present-with-undefined for tighter checks.
Code Solution
SolutionRead Only
type User = {
id: string; // required
name: string; // required
email?: string; // optional
}
const u1: User = { id: 'u1', name: 'Ava' };
// Safe update (shallow copy)
const u2: User = { ...u1, email: 'ava@example.com' };
// Narrow optional
if (u2.email) {
console.log(u2.email.toLowerCase());
}
// With exactOptionalPropertyTypes, “missing” vs “undefined” differs