scipper
scipper

Reputation: 3153

Type 'null' is not assignable to type '() => void | null'

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.

Upvotes: 11

Views: 15644

Answers (1)

Fenton
Fenton

Reputation: 251192

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.

Upvotes: 27

Related Questions