Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a difference between a variable with a ? or undefined type in Typescript

In Typescript there are two different methods of saying that a property can be undefined when creating an interface:

Method 1:

interface m1 {
    prop?: randomType; // type is (randomType | undefined)
}

Method 2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface m2 {
    prop: randomType|undefined; // type is (randomType | undefined)
}

The only immediately apparent between these two that I have noticed is that when hovering over prop IntelliSense will show undefined in blue for Method 1 and green for Method 2.

Are there any other differences between these?

>Solution :

To make it simple : with ? the field becomes optional :

type randomType = {}

interface M1 {
  prop?: randomType; // type is (randomType | undefined)
}

interface M2 {
  prop: randomType | undefined; // type is (randomType | undefined)
}

const m1: M1 = {} // OK
const m2: M2 = {} // NOK
const m22: M2 = { prop: undefined } // OK

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading