What are optional properties and parameters in TypeScript?
Why Interviewers Ask This
This is a classic screening question for TypeScript roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
Optional properties in interfaces and type aliases are marked with a ? after the property name: interface User { name: string; email?: string; } — email may or may not be present. When accessing optional properties, TypeScript requires checking for undefined first (unless using optional chaining user.email?.toUpperCase()). Optional function parameters are also marked with ?: function greet(name: string, greeting?: string): string { return (greeting ?? "Hello") + ", " + name; }. Optional parameters must come after required parameters. Default parameters are similar but provide a fallback value: function greet(name: string, greeting = "Hello"): string { ... } — TypeScript infers the parameter is optional and of the default value's type. The difference: optional parameters can be explicitly passed as undefined; default parameters also handle undefined by substituting the default.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.