Optional Interface Property
Write a TypeScript function that takes an object with a required name property and an optional age property (marked with ?). Return the age value if provided, or 0 if undefined. The ? after a property name in an interface marks it as optional, meaning it can be either the specified type or undefined.
Optional properties are declared with a question mark: age?: number. This means age can be number or undefined. When accessing an optional property, TypeScript forces you to check for undefined before using it, preventing null pointer errors at compile time. This is a key difference from JavaScript where accessing a missing property returns undefined silently.
Optional properties are essential for representing objects where some fields may not always be present. They work with interfaces, type aliases, and class properties. The --strictNullChecks compiler option (enabled by default in strict mode) ensures optional properties are handled safely.
Time complexity is O(1). Space complexity is O(1). The optional modifier is a compile-time concept with no runtime overhead.
Edge cases include missing optional property (returns undefined which the function handles), explicitly passing undefined for an optional property, and combining optional with readonly or other modifiers.
Example Input & Output
Age provided again
Age is provided
Age is missing, return 0
Age provided again
Missing age returns 0
Algorithm Flow

Solution Approach
Best Answers
interface Person {
name: string;
age?: number;
}
function solution(p: Person): number {
return p.age !== undefined ? p.age : 0;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
