Marek
Marek

Reputation: 4081

Method return type with null in typescript

My question is short and I will give an example. I have some class:

class A {
  public property: Property;

  constructor(data: any) {
    this.property = this.parseProperty(data)
  }

  private parseProperty(): Property {
    return data.property
      ? {
          name: data.property.name,
          code: data.property.code,
        }
      : null;
  }
}

Given the example above, should I add '| null' to the return type of parseProperty method? Is there any implication to do so? Also, should I add | null to the property declaration? It works perfectly fine without it.

Upvotes: 4

Views: 4501

Answers (1)

JB Nizet
JB Nizet

Reputation: 692023

It depends.

If you configured your TypeScript project to use strict null checks, then a value of type Poperty may not be null. And your code will thus only compile if you use

public property: Property | null;

and

private parseProperty(): Property | null {

If you didn't, then it's basically a matter of choice regarding the readability and the verbsity of your code. You could choose to be more verbose, but clearer about what the variable can be by using

public property: Property | null;

By reading that code, you or your colleagues will remember that this value could be null, and that this case needs to be taken into account.

Or you could decide that this is implicit or too verbose, and leave it as it is.

Sometimes, it's obvious that values could be null. Sometimes, it's obvious that they can't possibly be null. Sometimes, it's not obvious at all, and making it explict can help, even without activating strict null checks.

Upvotes: 7

Related Questions