What's the difference between ?: and | undefined in TypeScript? What's the difference between ?: and | undefined in TypeScript? typescript typescript

What's the difference between ?: and | undefined in TypeScript?


One difference is that cost: number | undefined; requires the property to exist, and have a value whose type is number or undefined. In contrast, cost?: number permits the property to not exist at all.

This fails to compile:

interface Fruit {    cost: number | undefined;}const x: Fruit = {};

For it to work, you'd have to do:

interface Fruit {    cost: number | undefined;}const x: Fruit = { cost: undefined };

But this succeeds:

interface Fruit {    cost?: number;}const x: Fruit = {};

Explicitly typing undefined can be tedious when an alternative is available, so you'll probably prefer the cost?: number option.