scripter
scripter

Reputation: 115

Why does Typescript discourage setting values to null?

I don't understand the reasoning behind non nullable types and Typescript's strictNullChecks flag. I always set the value of a variable to null when I am sure I am done with it to release it from memory and the GC can collect it. My tests have shown that it speeds up the execution of the JavaScript code by many times, especially in long, and deep loops. Is this a bad practice? Should some types of variables be set to null and not others?

Upvotes: 5

Views: 3948

Answers (2)

Richard Haddad
Richard Haddad

Reputation: 1014

In most cases you don't have to delete variable values yourself. It may be a design flaw. Also note that if you want to delete an object property value, it may be more consistent to use that:

    delete myObject.attr;  // set 'undefined'

I don't understand the reasoning behind non nullable types and Typescript's strictNullChecks flag.

To understand the logic behind, check this sample:

// strictNullChecks: false

interface Sample {
  color: string;
  width: number;
}

function doSomething(sample: Sample): Sample {
  if(sample.width > 10) {
    return null;
  }
  return sample;
}

const first: Sample = {
  color: 'red',
  width: 15
};

const second: Sample = doSomething(first);

console.log(second.width);  // Uncaught TypeError: Cannot read property 'width' of null

Playground

This code compiles only without strictNullChecks flag. In this context when the code runs we have a beautiful error: Uncaught TypeError: Cannot read property 'width' of null.

Check the function doSomething. It returns a Sample type, but without the flag we can return null. The problem here is that when we call this function, the value returned will be manipulated as a Sample => There is a inconsistence between the type and its real value type. It's a huge cause of errors.

I like to think that TS typings must reflect at the best real types of values.

Upvotes: 1

winwiz1
winwiz1

Reputation: 3174

The reasoning is to prevent some run-time errors including console.log(null.printWhyNullIsBad()); by catching those errors at the compilation time while assuming that people who write loops so deep and so nested that it stretches the modern JS garbage collectors to their limits can write that kind of code in C/C++ and run it using WebAssembly.

Upvotes: 3

Related Questions