Node Skip Typeerror: Cannot Read Property 'marketplaceasin' of Undefined

As a JavaScript programmer, I'm sure you've encountered the frustrating runtime TypeError Cannot read properties of undefined .TypeScript gives yous 2 ways of interpreting null  and undefined types, also known as Type Check Modes, and one of them tin avert this easily overlooked TypeError.

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

TypeScript 2.0 introduced Strict Type Check Fashion (also referred to equally strict null checking way). Strict Type Check differs from Regular Type Check because it considers goose egg  and undefined types of their own.

I'll testify you how Regular Type Check handles undefined (the same applies to goose egg ) and how Strict Type Check prevents you from introducing unwanted beliefs in our code, like that infamous TypeError Cannot read backdrop of undefined .

When undefined becomes a problem

The function translatePowerLevel beneath takes a number as argument and returns strings ane , 2 , many or it's over 9000! .

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

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

yamcha

Yamcha's Ability Level

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

The translatePowerLevelpart render value is typed explicitly every bit string , simply information technology is possibly as well returning undefined  when the argument powerLevel  has the value0. Why is TypeScript not triggering an error?

In Regular Type Cheque Style, TypeScript is aware that a function might render undefined . Only at the same time, TypeScript infers the return type to be just of type string because TypeScript is widening the undefined type to cord blazon.

As another example, if you lot assign cipher or undefined to variables while in Regular Type Check Mode, TypeScript will infer these variables to exist of blazon any .

              const java = null;                
const tea = undefined;

Interpreting undefined or aught as subtypes of all other types tin can atomic number 82 to runtime issues. For example, if y'all effort to get the length of the upshot of translateNumber(0) , which is undefined , JavaScript will throw this TypeError at runtime: Cannot read backdrop of undefined (reading 'length').

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

Unfortunately, TypeScript's Regular Blazon Check Way is not able to alert you lot to when you may have made that mistake.

Strict Blazon Check Mode to the Rescue

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

How to Enable Strict Blazon Bank check Mode in TypeScript

In the root of your project, at that place should be a tsconfig.json file. This is the TypeScript's configuration file and yous can read more than about information technology here.

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

Within compilerOptions property, all we need to do is add the holding "strictNullChecks": true .

It will await something like this:

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

Now that nosotros accept switched to Strict Blazon Cheque Mode, TypeScript throws this mistake for translatePowerLevel function: Function lacks catastrophe return argument and return blazon does not include 'undefined' .

That mistake bulletin is telling you the function is returning undefined implicitly, only its return type does non include undefined in information technology.

Crawly! TypeScript is now enlightened the return blazon does non match all possible return values, and this could pb to problems at runtime! Merely how can you lot match the return type to all possible return values?

You can either add a return argument so the office always returns a string (solution #1), or change the return blazon from string to string | undefined (solution #ii).

Match All Possible Return Values: Solution #1

Adding a return statement so information technology is always explicitly returning a value - in the code below, it is now returning the string zero .

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

Match All Possible Return Values: Solution #2

Make the undefined return blazon explicit so wherever translatePowerLevel is used, you lot accept to handle nullish values equally well.

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

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

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

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

There's no reason not to use Strict Type Check Mode

Now you understand how TypeScript interprets nothing and undefined types and how you tin migrate your project to Strict Mode.

If you are starting a new project, y'all should definitely enable Strict Blazon Bank check Mode from the beginning. And in case you will migrate from Regular to Strict Type Check, our team can help with strategies to practice and so in a less painful mode.

At Bitovi nosotros highly recommend using - or migrating to - Strict Blazon Check Way for Angular application development, as it can help you produce better, more reliable code. If you need help with building amazing web apps experience free to reach us at bitovi.com .

rodriguezhiselon.blogspot.com

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

Belum ada Komentar untuk "Node Skip Typeerror: Cannot Read Property 'marketplaceasin' of Undefined"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel