Reputation: 766
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?
Upvotes: 1
Views: 625
Reputation: 649
In the tsconfig.json file, under "compilerOptions", set the strict
property to true
. This ensures that the initialized object matches as defined in the MyObject class.
{
"compilerOptions": {
// ................
"strict": true,
//..................
}
}
Upvotes: 1
Reputation: 50222
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 totrue
], 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.
Upvotes: 0