Home > database >  Why won't typescript allow me to set undefined when it is allowed to set it?
Why won't typescript allow me to set undefined when it is allowed to set it?

Time:08-06

Consider this class:

class MyObject {
    myVar: string;
}

When I initially construct MyObject, myVar field will be set to an undefined, yet when I try to set the variable to an undefined, it will complain. I understand that I can pipe the myVar to allow undefined like myVar: string | undefined;

const obj: MyObject = new MyObject();
console.log(obj.myVar);                           // undefined
console.log(typeof obj.myVar === 'undefined');    // true

obj.myVar = undefined;                            // not allowed

To me, the purpose of not allowing an undefined is to indicate that this variable can never be undefined. But clearly that is not true. So then, what is the purpose of not allowing us to set it to an undefined?

CodePudding user response:

undefined is just the default value of myVar. Typescript ensures that you assign only a string datatype to myVar but during any initialization of the MyObject class, its properties (e.g. myVar) would be undefined by default.

CodePudding user response:

You can enable a compiler warning by setting strictPropertyInitialization: true.

When set to true, TypeScript will raise an error when a class property was declared but not set in the constructor.

Default: true if [strict is set to true], false otherwise.

Note: In the example code there, they also demonstrate that fields with default initializers don't need to be explicitly set in the constructor to satisfy this warning check.

  • Related