tell me the difference between undefined and? 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.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top