17. What is the ? operator in TypeScript, and where is it used?

The ? operator in TypeScript is used to define optional values, both for function parameters and object properties. When ? is used on an object property or function parameter, it means that this value is optional and can be omitted.

Example:

interface Person { name: string; age?: number; } const john: Person = { name: 'John' }; // The 'age' property is optional.

The ? operator can also be used for handling null or undefined types in expressions.

let value: string | undefined; let result = value?.length; // Safe access to 'length' even if value is undefined.

In this example, ?. is the optional chaining operator, which allows safe access to object properties without worrying about errors if the object is null or undefined.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.