1

In TypeScript, is there any difference between the following?

private dog: TDog | undefined;

vs

private dog?: TDog;

Also, what is the ? called?

2

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.