Typeerror: Cannot Read Property 'run' of Null

As a JavaScript programmer, I'm sure you've encountered the frustrating runtime TypeError Cannot read backdrop of undefined .TypeScript gives you 2 ways of interpreting null  and undefined types, too known as Type Check Modes, and one of them can avert this hands disregarded TypeError.

Until TypeScript 2.0, at that place was only one blazon check mode - regular - and it considers null  and undefined as subtypes of all other types. This means null and undefined values are valid values for all types.

TypeScript 2.0 introduced Strict Blazon Check Mode (also referred to as strict nothing checking way). Strict Type Cheque differs from Regular Type Check because it considers cipher  and undefined types of their own.

I'll show y'all how Regular Type Check handles undefined (the same applies to cypher ) and how Strict Blazon Bank check prevents you from introducing unwanted behavior in our code, like that infamous TypeError Cannot read properties of undefined .

When undefined becomes a problem

The office translatePowerLevel beneath takes a number equally argument and returns strings i , 2 , many or it's over 9000! .

              function translatePowerLevel(powerLevel: number): cord {                
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === two) {
render 'ii';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
render 'information technology\'s over 9000!';
}
}

Still, this code doesn't handle 0, a valid input - yes, looking at y'all, Yamcha.

yamcha

Yamcha's Power Level

When JavaScript reaches the finish of a part that has no explicit return, information technology returns undefined .

The translatePowerLevelfunction return value is typed explicitly as string , but it is peradventure also returning undefined  when the argument powerLevel  has the value0. Why is TypeScript not triggering an error?

In Regular Type Bank check Way, TypeScript is enlightened that a function might return undefined . Simply at the same time, TypeScript infers the return type to be only of type string because TypeScript is widening the undefined type to string type.

As another example, if you assign null or undefined to variables while in Regular Type Cheque Way, TypeScript will infer these variables to exist of type whatever .

              const coffee = null;                
const tea = undefined;

Interpreting undefined or null as subtypes of all other types tin lead to runtime problems. For example, if y'all endeavour to get the length of the result of translateNumber(0) , which is undefined , JavaScript volition throw this TypeError at runtime: Cannot read backdrop of undefined (reading 'length').

              const powerLevel = translatePowerLevel(0); // undefined                
console.log(powerLevel.length); // Uncaught TypeError: Cannot read properties of undefined (reading 'length')

Unfortunately, TypeScript's Regular Type Cheque Mode is non able to alert you lot to when y'all may accept made that mistake.

Strict Blazon Check Fashion to the Rescue

Strict Type Check Mode changes how TypeScript interprets undefined and null values. But first, let'south enable Strict Type Check Mode.

How to Enable Strict Type Check Way in TypeScript

In the root of your project, there should be a tsconfig.json file. This is the TypeScript'south configuration file and you tin read more than about it here.

              // tsconfig.json example                
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": truthful,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

Inside compilerOptions property, all nosotros need to practise is add together the property "strictNullChecks": truthful .

It will look something like this:

              // tsconfig.json                
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": truthful,
"outFile": "../../built/local/tsc.js",
"sourceMap": true,
"strictNullChecks": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

Now that nosotros accept switched to Strict Blazon Check Way, TypeScript throws this error for translatePowerLevel function: Function lacks ending return argument and render type does not include 'undefined' .

That mistake message is telling you the part is returning undefined implicitly, but its return type does non include undefined in it.

Crawly! TypeScript is at present aware the return type does non match all possible return values, and this could atomic number 82 to issues at runtime! Just how can y'all match the render type to all possible return values?

Y'all can either add a return statement and then the function always returns a cord (solution #i), or change the return type from string to string | undefined (solution #2).

Match All Possible Return Values: Solution #1

Calculation a return statement so information technology is always explicitly returning a value - in the code below, it is at present returning the string cypher .

              // Solution #1: add a render argument so information technology always returns a string                
function translatePowerLevel(powerLevel: number): string {
if (powerLevel === ane) {
render 'ane';
}
if (powerLevel === two) {
render 'ii';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'due south over 9000!';
}
// new render argument
return 'zero';
}

Match All Possible Return Values: Solution #2

Make the undefined return blazon explicit and so wherever translatePowerLevel is used, y'all have to handle nullish values as well.

              // Solution #2: render type equally cord | undefined                
function translatePowerLevel(powerLevel: number): string | undefined {
if (powerLevel === one) {
return 'one';
}
if (powerLevel === ii) {
return '2';
}
if (powerLevel > 2 && powerLevel <= 9000) {
render 'many';
}
if (powerLevel > 9000) {
return 'information technology\'due south over 9000!';
}
}

If you were to compile the post-obit code over again using Solution #2, TypeScript would throw the error Object is possibly 'undefined' .

              const powerLevel = translatePowerLevel(0); // undefined                
console.log(powerLevel.length); // Object is peradventure 'undefined'.

When yous choose a solution like Solution #2, TypeScript expects you to write code that handles possible nullish values.

At that place'southward no reason non to utilize Strict Type Check Way

Now you understand how TypeScript interprets null and undefined types and how yous can migrate your project to Strict Manner.

If you are starting a new project, you should definitely enable Strict Type Check Fashion from the showtime. And in case you will migrate from Regular to Strict Type Check, our team can assist with strategies to exercise and then in a less painful manner.

At Bitovi we highly recommend using - or migrating to - Strict Type Bank check Mode for Angular application development, every bit information technology tin assist you lot produce better, more reliable lawmaking. If you need help with building astonishing web apps feel free to accomplish united states of america at bitovi.com .

martinezalackeen.blogspot.com

Source: https://www.bitovi.com/blog/how-to-avoid-the-infamous-cannot-read-properties-of-undefined-with-typescript

Related Posts

0 Response to "Typeerror: Cannot Read Property 'run' of Null"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel