Search code examples
typescriptundefined

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:

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