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?
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
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.