I basically understand TS2322, but in this case, I don't get it.
I have a given class definition like this:
export class MyFaultyClass {
functionOrNull: () => void | null;
constructor() {
this.functionOrNull = null; // <- here comes the error TS2322
}
}
My question
Why can't I assign null to the defined property?
My expectation
constructor() {
this.functionOrNull = null; // OR
this.functionOrNull = () => {};
}
Edit
Here is a "working" example: typescriptlang.org/playground Needs strictNullChecks to be enabled.
Here's the fix, then the explanation:
export class MyWorkingClass {
functionOrNull: { () : void } | null;
constructor() {
this.functionOrNull = null; // <- Joy
}
}
So when you say () => void | null
the function will return either void
or null
.
When you say { () : void } | null;
it is either a function returning void
, or it is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With