How is the ? operator different than including undefined in the type?

Viewed 92
4 Answers

Using ? means you can omit that value, but using undefined means you must provide either a string or undefined.

// Note: Tested with Typescript 3.8.3
type A = { a? : string }
type B = { b: string | undefined }

const objectA: A = {} // OK!
const objectB: B = {} // ERROR: property 'b' is missing on type B

In general, I think that using ? is what you want most of the time, since you want the value to default to undefined. Very rarely have I ever come across a case where I want users to explicitly enter undefined as a value.

Utilizing the ? means that A may or may not exist, and A can be a string and undefined. Defining an undefined type doesn't mean it isn't there.

The undefined has to do with A's content, and ? sign ios related to its existence. You can use both together, but if you're sure that A will always be there, use just undefined.

There's a slight distinction between having an object with a property being set explicitly to undefined, and an object with that property not being there at all.

type A = {a: string | undefined} // No "?", so this enforces that key "a" must be present!

let varA: A = { a: undefined } // OK
let varB: A = {} // Not OK, because key "a" is not present

This TypeScript, it will cause an error in JavaScript.

The question mark means the property is optional, | undefined is pointless as all properties can have undefined assigned as it's value.

If you define the type

type A = {a?: string, b: string}

then you can define a variable without a

let x: A = { b: 'some value' };

type A = {a: string | undefined} offers nothing over type A = {a: string} as the a property still needs to be in the declaration and a string can already have undefined assigned to it.

let x: A = {} is an error as you didn't supply a and let x: A = { a: undefined } is allowed with type A = {a: string}

This make | undefined pointless as any property can have undefined assigned to it anyway.

Related