Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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.

like image 546
scipper Avatar asked Nov 24 '17 10:11

scipper


1 Answers

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.

like image 100
Fenton Avatar answered Sep 18 '22 07:09

Fenton