Back to questions
JuniorTheoryCommon
What does tsc report for this file?
type User = { name: string; age?: number };
const u: User = { name: "Ann" };
console.log(u.age + 1);An error: u.age may be undefined
- Expecting tsc to let
u.age + 1through and printNaN: an optional property reads asnumber | undefined, so arithmetic on it needs a check or a default. - Expecting the literal to need
age: the?makes the property optional, so{ name: "Ann" }is a validUser; only usingageneeds care.
- How would you fix line 3 so that a missing age counts as
0? - How does
age?: numberdiffer fromage: number | undefined?