Ben
Ben

Reputation: 16669

Typescript ? vs undefined

In TypeScript, is there any difference between the following?

private dog: TDog | undefined;

vs

private dog?: TDog;

Also, what is the ? called?

Upvotes: 1

Views: 43

Answers (1)

Skyone
Skyone

Reputation: 111

? operator means that parameter is optional, it’s not necessary to pass it in component/function.

undefined means that parameter must be passed in but its value may be undefined.

A simple example:

type A = {
    a?: string
}
type B = {
    a: string | undefined
}

const a: A = { }
const b: B = { }

Paste it into VSCode and you can see:

enter image description here

I once read an article about this. Hope it helps you.

Upvotes: 1

Related Questions