javascripttypescriptstrictnullchecks

What should I return when object is not found in TypeScript using strict mode?


Here's the snippet of code in typescript with strictNullChecks: true

getItem(key: string): T {
    let index: number = this.contains(key); // returns -1 if not found
    if (index === -1) {
        return null; // error null is not assignable to type 'T'
    } 
    return this.map[index].value;
  }

As you can see I can't return null when I didn't find element because of a compilation error:

error 'null' is not assignable to type 'T'

What should I return instead of null? What is the best practice?


Solution

  • With strict null checks, any function that is returning something which could be 'not found' should have return type declared as Something | undefined, and it should return undefined value in "not found" case.

    It's also possible to use null instead of undefined, both as type and as return value, but the choice was made and TypeScript type system uses undefined, not null for representing uninitialized and optional values - for example, the type of optional property (declared with ? sign) is T | undefined.

    See also this quote mentioned by user cale_b in comments:

    the rational is JavaScript has two concepts to refer to the empty sentinel value, most other programming languages just have one. Moreover, undefined is always present, as all uninitialized values have the value undefined at run time. null on the other hand is avoidable, specially if you are not using any APIs that produce it, e.g. DOM, which the TypeScript compiler does not use.