Code Logo

Optional Interface Property

Published at25 Jul 2026
TypeScript Generics & Advanced Types Easy 0 views
Like0

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

Example 1
Input
{"name":"Eve","age":40}
Output
40
Explanation

Age provided again

Example 2
Input
{"name":"Alice","age":30}
Output
30
Explanation

Age is provided

Example 3
Input
{"name":"Bob"}
Output
0
Explanation

Age is missing, return 0

Example 4
Input
{"name":"Charlie","age":25}
Output
25
Explanation

Age provided again

Example 5
Input
{"name":"Diana"}
Output
0
Explanation

Missing age returns 0

Algorithm Flow

Recommendation Algorithm Flow for Optional Interface Property
Recommendation Algorithm Flow for Optional Interface Property

Solution Approach

interface Person {
  name: string;
  age?: number;
}

function solution(p: Person): number {
  return p.age !== undefined ? p.age : 0;
}

Best Answers

typescript - Approach 1
interface Person {
  name: string;
  age?: number;
}

function solution(p: Person): number {
  return p.age !== undefined ? p.age : 0;
}