Angular Typeerror: Cannot Read Property of Undefined
Every bit a JavaScript developer, I'chiliad sure yous've encountered the frustrating runtime TypeError Until TypeScript 2.0, there was merely i blazon check way - regular - and it considers TypeScript two.0 introduced Strict Type Cheque Mode (also referred to as strict null checking mode). Strict Type Cheque differs from Regular Type Check considering information technology considers I'll show you how Regular Type Bank check handles The role translatePowerLevel below takes a number as argument and returns strings Nevertheless, this code doesn't handle 0, a valid input - yep, looking at yous, Yamcha. Yamcha's Power Level When JavaScript reaches the end of a office that has no explicit render, it returns The In Regular Type Check Mode, TypeScript is aware that a part might return As another example, if you assign Interpreting Unfortunately, TypeScript's Regular Type Check Mode is non able to alert you to when you may have made that fault. Strict Type Check Way changes how TypeScript interprets In the root of your project, at that place should exist a Inside It will look something like this: At present that we have switched to Strict Type Check Mode, TypeScript throws this error for That error message is telling you the function is returning Awesome! TypeScript is now enlightened the return type does not friction match all possible return values, and this could lead to bug at runtime! Only how can you match the return type to all possible return values? Y'all can either add a return statement and so the part always returns a Adding a return statement so information technology is always explicitly returning a value - in the lawmaking below, it is at present returning the Make the If you were to compile the post-obit code once more using Solution #two, TypeScript would throw the mistake When you lot choose a solution like Solution #two, TypeScript expects you to write code that handles possible Now you sympathise how TypeScript interprets If you are starting a new project, you should definitely enable Strict Blazon Bank check Mode from the commencement. And in case y'all will migrate from Regular to Strict Type Cheque, our team can help with strategies to practice so in a less painful way. At Bitovi we highly recommend using - or migrating to - Strict Type Check Mode for Angular application development, as it can help you lot produce better, more reliable code. If you lot need help with building astonishing web apps feel free to reach us at bitovi.com . Cannot read properties of undefined
.TypeScript gives you ii ways of interpreting null
and undefined
types, also known equally Type Check Modes, and one of them can avoid this hands disregarded TypeError. nothing
and undefined
every bit subtypes of all other types. This means null
and undefined
values are valid values for all types. null
and undefined
types of their own. undefined
(the aforementioned applies to null
) and how Strict Type Cheque prevents you from introducing unwanted behavior in our code, like that infamous TypeError Cannot read backdrop of undefined
.When undefined becomes a problem
one
, two
, many
or it's over 9000!
.
function translatePowerLevel(powerLevel: number): cord {
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!';
}
} undefined
. translatePowerLevel
function return value is typed explicitly as cord
, but information technology is possibly also returning undefined
when the argument powerLevel
has the value0. Why is TypeScript not triggering an mistake? undefined
. Simply at the aforementioned fourth dimension, TypeScript infers the return type to be only of type string
because TypeScript is widening the undefined
type to string
type. cypher
or undefined
to variables while in Regular Blazon Check Mode, TypeScript will infer these variables to be of type any
.
const coffee = null;
const tea = undefined; undefined
or cipher
as subtypes of all other types tin pb to runtime problems. For example, if you try to get the length of the result 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')Strict Type Check Mode to the Rescue
undefined
and zilch
values. But kickoff, let's enable Strict Type Cheque Mode. How to Enable Strict Type Check Manner in TypeScript
tsconfig.json file
. This is the TypeScript's configuration file and you tin can read more about it here.
// tsconfig.json case
{
"compilerOptions": {
"module": "system",
"noImplicitAny": truthful,
"removeComments": truthful,
"preserveConstEnums": truthful,
"outFile": "../../congenital/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
} compilerOptions
belongings, all we need to practise is add the belongings "strictNullChecks": true
.
// tsconfig.json
{
"compilerOptions": {
"module": "system",
"noImplicitAny": truthful,
"removeComments": true,
"preserveConstEnums": truthful,
"outFile": "../../congenital/local/tsc.js",
"sourceMap": true,
"strictNullChecks": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}translatePowerLevel
office: Function lacks ending return statement and return type does not include 'undefined'
. undefined
implicitly, only its return type does not include undefined
in it.string
(solution #one), or change the return type from cord
to cord | undefined
(solution #2). Match All Possible Return Values: Solution #1
string zilch
.
// Solution #ane: add a render statement then it always returns a string
part translatePowerLevel(powerLevel: number): string {
if (powerLevel === 1) {
return 'i';
}
if (powerLevel === two) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'southward over 9000!';
}
// new return statement
return 'zero';
} Match All Possible Return Values: Solution #ii
undefined
return blazon explicit so wherever translatePowerLevel
is used, you have to handle nullish
values equally well.
// Solution #two: return type as string | undefined
part translatePowerLevel(powerLevel: number): cord | undefined {
if (powerLevel === ane) {
return 'one';
}
if (powerLevel === 2) {
return '2';
}
if (powerLevel > ii && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it\'s over 9000!';
}
} Object is possibly 'undefined'
.
const powerLevel = translatePowerLevel(0); // undefined
panel.log(powerLevel.length); // Object is perchance 'undefined'. nullish
values.There'southward no reason not to use Strict Blazon Check Fashion
goose egg
and undefined
types and how y'all tin drift your project to Strict Mode.
Source: https://www.bitovi.com/blog/how-to-avoid-the-infamous-cannot-read-properties-of-undefined-with-typescript
Postar um comentário for "Angular Typeerror: Cannot Read Property of Undefined"