Optional properties and parameters ?
A ? after the name says the property or parameter may be missing, and its type includes undefined.
You put ? right after the name: bio?: string in a type or interface, name?: string in a parameter. It means you may leave it out.
To the type checker, the value is string | undefined. Before you use it as a string, you have to check that it exists. That way tsc stops you from calling methods on undefined.
An optional parameter must come after the required ones. If you pass nothing, its value is undefined.
In lesson 03.01 you see it in bio?: string;: the profile may have no bio. The ? is type-only syntax: it is gone when Node runs the code, so it adds no check at runtime.
type User = { name: string; bio?: string };
Reach for it when: a value can legitimately be absent, like a bio, or when a parameter has a sensible behavior without it.
Examples
Common mistake
type User = { name: string; bio?: string };
const u: User = { name: "Ana" };
console.log(u.bio.toUpperCase());Why: bio may be undefined, and undefined has no methods. tsc warns you before it fails at runtime.
How to write it: Check first: if (u.bio !== undefined), or use u.bio?.toUpperCase().
Common mistake
function f(a?: number, b: number): number {
return (a ?? 0) + b;
}Why: A required parameter cannot follow an optional one.
How to write it: Put the required ones first: f(b: number, a?: number).
