Skip to content Skip to sidebar Skip to footer

Cannot Read Property 'statuscode' of Undefined Ode Js

As a JavaScript developer, I'm sure yous've encountered the frustrating runtime TypeError Cannot read backdrop of undefined .TypeScript gives you two ways of interpreting cypher  and undefined types, also known equally Blazon Check Modes, and i of them can avoid this hands overlooked TypeError.

Until TypeScript two.0, in that location was only i type check way - regular - and it considers null  and undefined equally subtypes of all other types. This means zip and undefined values are valid values for all types.

TypeScript 2.0 introduced Strict Type Check Mode (also referred to as strict goose egg checking mode). Strict Type Check differs from Regular Blazon Cheque considering it considers null  and undefined types of their own.

I'll show y'all how Regular Type Cheque handles undefined (the same applies to nix ) 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 role translatePowerLevel below takes a number as argument and returns strings one , ii , many or it's over 9000! .

              function translatePowerLevel(powerLevel: number): string {                
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'s over 9000!';
}
}

However, this code doesn't handle 0, a valid input - yes, looking at you, Yamcha.

yamcha

Yamcha's Power Level

When JavaScript reaches the end of a role that has no explicit return, it returns undefined .

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

In Regular Blazon Bank check Mode, TypeScript is aware that a function might render undefined . Only at the same time, TypeScript infers the return type to be simply of type string because TypeScript is widening the undefined type to cord blazon.

As another example, if you assign null or undefined to variables while in Regular Blazon Check Mode, TypeScript volition infer these variables to be of blazon any .

              const coffee = null;                
const tea = undefined;

Interpreting undefined or null equally subtypes of all other types can lead to runtime problems. For example, if you try to get the length of the event of translateNumber(0) , which is undefined , JavaScript will throw this TypeError at runtime: Cannot read properties of undefined (reading 'length').

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

Unfortunately, TypeScript'due south Regular Blazon Check Mode is non able to warning you to when you may have fabricated that mistake.

Strict Type Check Way to the Rescue

Strict Type Check Style changes how TypeScript interprets undefined and null values. But first, let's enable Strict Type Cheque Way.

How to Enable Strict Blazon Check Mode in TypeScript

In the root of your projection, there should be a tsconfig.json file. This is the TypeScript's configuration file and you lot can read more well-nigh it hither.

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

Within compilerOptions belongings, all nosotros need to do is add the belongings "strictNullChecks": true .

It will expect something like this:

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

Now that we take switched to Strict Type Check Mode, TypeScript throws this error for translatePowerLevel function: Function lacks ending render statement and return type does non include 'undefined' .

That fault message is telling you lot the function is returning undefined implicitly, but its render type does not include undefined in information technology.

Awesome! TypeScript is now aware the return blazon does not lucifer all possible render values, and this could lead to problems at runtime! But how tin yous lucifer the render type to all possible render values?

You can either add a return statement so the function always returns a string (solution #1), or change the render type from string to string | undefined (solution #ii).

Match All Possible Return Values: Solution #1

Adding a return argument and then information technology is e'er explicitly returning a value - in the code below, it is now returning the string nothing .

              // Solution #1: add a render statement and then it e'er returns a string                
function translatePowerLevel(powerLevel: number): string {
if (powerLevel === one) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
render 'information technology\'s over 9000!';
}
// new return statement
return 'zero';
}

Match All Possible Return Values: Solution #2

Brand the undefined return type explicit so wherever translatePowerLevel is used, yous accept to handle nullish values as well.

              // Solution #ii: return blazon equally string | undefined                
part translatePowerLevel(powerLevel: number): string | undefined {
if (powerLevel === 1) {
return 'i';
}
if (powerLevel === 2) {
return '2';
}
if (powerLevel > ii && powerLevel <= 9000) {
render 'many';
}
if (powerLevel > 9000) {
render 'it\'s over 9000!';
}
}

If yous were to compile the following code again using Solution #2, TypeScript would throw the fault Object is possibly 'undefined' .

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

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

At that place'south no reason not to use Strict Blazon Check Mode

Now you sympathise how TypeScript interprets null and undefined types and how you tin migrate your project to Strict Style.

If you are starting a new project, you lot should definitely enable Strict Type Check Fashion from the beginning. And in case you will migrate from Regular to Strict Type Cheque, our team can help with strategies to practice then in a less painful way.

At Bitovi we highly recommend using - or migrating to - Strict Type Check Style for Angular application development, as it tin can aid you lot produce amend, more reliable code. If you need assistance with edifice amazing web apps feel free to accomplish united states of america at bitovi.com .

whitakerwhisip.blogspot.com

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

Post a Comment for "Cannot Read Property 'statuscode' of Undefined Ode Js"