Cannot Read Property 'scale' of Undefined in Time

As a JavaScript developer, I'chiliad sure you've encountered the frustrating runtime TypeError Cannot read properties of undefined .TypeScript gives you two ways of interpreting nothing  and undefined types, also known equally Type Bank check Modes, and one of them can avoid this easily overlooked TypeError.

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

TypeScript two.0 introduced Strict Type Bank check Mode (also referred to as strict null checking fashion). Strict Type Bank check differs from Regular Type Cheque because it considers null  and undefined types of their own.

I'll show you how Regular Type Check handles undefined (the aforementioned applies to null ) and how Strict Type Check prevents you from introducing unwanted beliefs in our code, like that infamous TypeError Cannot read properties of undefined .

When undefined becomes a problem

The function translatePowerLevel below takes a number equally statement and returns strings one , two , many or it's over 9000! .

              function translatePowerLevel(powerLevel: number): string {                
if (powerLevel === one) {
render '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 lot, Yamcha.

yamcha

Yamcha's Power Level

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

The translatePowerLevelfunction render value is typed explicitly as string , but it is perhaps besides returning undefined  when the argument powerLevel  has the value0. Why is TypeScript not triggering an fault?

In Regular Type Check Mode, TypeScript is enlightened that a function might return undefined . But at the same time, TypeScript infers the render type to exist only of type string because TypeScript is widening the undefined type to string blazon.

As another example, if y'all assign zip or undefined to variables while in Regular Blazon Check Mode, TypeScript will infer these variables to be of type whatsoever .

              const coffee = naught;                
const tea = undefined;

Interpreting undefined or goose egg equally subtypes of all other types can lead to runtime bug. For example, if you try to go the length of the result 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's Regular Type Check Mode is not able to alarm you lot to when you may have made that mistake.

Strict Type Cheque Way to the Rescue

Strict Type Cheque Manner changes how TypeScript interprets undefined and null values. But first, allow's enable Strict Type Check Mode.

How to Enable Strict Type Check Mode in TypeScript

In the root of your projection, there should be a tsconfig.json file. This is the TypeScript'southward configuration file and you tin can read more than near information technology here.

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

Inside compilerOptions property, all we demand to do is add the belongings "strictNullChecks": true .

It will expect something like this:

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

At present that we have switched to Strict Type Check Mode, TypeScript throws this mistake for translatePowerLevel role: Function lacks ending return statement and return type does non include 'undefined' .

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

Awesome! TypeScript is now enlightened the return type does not match all possible return values, and this could lead to bug at runtime! Simply how tin you match the return type to all possible render values?

Y'all can either add a render argument so the function e'er returns a string (solution #1), or modify the render blazon from string to string | undefined (solution #2).

Lucifer All Possible Return Values: Solution #i

Adding a return argument then information technology is always explicitly returning a value - in the lawmaking below, it is now returning the string naught .

              // Solution #1: add a return argument so it ever returns a cord                
function translatePowerLevel(powerLevel: number): cord {
if (powerLevel === one) {
return 'one';
}
if (powerLevel === two) {
render 'ii';
}
if (powerLevel > two && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'southward over 9000!';
}
// new render statement
return 'cipher';
}

Match All Possible Render Values: Solution #two

Brand the undefined return type explicit and so wherever translatePowerLevel is used, you have to handle nullish values also.

              // Solution #2: return type every bit cord | undefined                
function translatePowerLevel(powerLevel: number): string | undefined {
if (powerLevel === 1) {
return '1';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > two && powerLevel <= 9000) {
render 'many';
}
if (powerLevel > 9000) {
return 'information technology\'s over 9000!';
}
}

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

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

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

There'due south no reason not to use Strict Type Bank check Style

Now you understand how TypeScript interprets null and undefined types and how you can drift your project to Strict Mode.

If you are starting a new project, you lot should definitely enable Strict Type Check Way from the starting time. And in case yous will migrate from Regular to Strict Blazon Check, our team can help with strategies to do and so in a less painful way.

At Bitovi we highly recommend using - or migrating to - Strict Type Cheque Mode for Angular application development, equally it tin assist you produce better, more reliable lawmaking. If you need aid with edifice astonishing web apps experience free to attain us at bitovi.com .

duffyandessomeho.blogspot.com

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

0 Response to "Cannot Read Property 'scale' of Undefined in Time"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel