Search code examples
typescriptoption-typeoptional-parameters

What's the difference between "?" and "| undefined"?


I'm wondering, is there a difference (actual or best practices wise) between

interface Fruit {
  cost?: number;
}

and

interface Fruit {
  cost: number | undefined;
}

If there is an actual difference in terms of behaviour, what is it?

If there isn't, why would one prefer | undefined or ?: (or vice versa)?

Sort of confused because I've seen both, and not sure if there's actually an actual reason for preferring one over the other, or if it's something that just boils down to preference.

Thanks!


Solution

  • 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.