Because TypeScript detected your property value can be null
or undefined
. In TypeScript, this feature called “strict null checks“. Let’s see the following example.
class Example {
doSomething(): void {
const username = 'David' as string | undefined;
const length = username.length;
// ~~~~~~~~
// Error: Object is possibly 'undefined'.
}
}
As you can see, TypeScript throws error “Object is possibly ‘undefined’” for username
object.
In order to fix that error, we have some ways as below:
Open tsconfig.json
and add "strictNullChecks": false
to angularCompilerOptions
{
...
"angularCompilerOptions": {
"strictNullChecks": false,
...
}
}
You can use IF condition to check datatype of property/variable.
class Example {
doSomething(): void {
const username = 'David' as string | undefined;
// use IF condition,
// the error gone away! :)
if (typeof username === 'string') {
const length = username.length;
}
}
}
You can add !
(exclamation mark) after a property/variable name. This feature is called “Non-null assertion operator“, basically it means that when you add the exclamation mark after a property/value, you are telling TypeScript that you are certain that value is not null
or undefined
.
class Example {
doSomething(): void {
const username = 'David' as string | undefined;
// add ! (exclamation mark) after the property/variable,
// the error gone away! :)
const length = username!.length;
}
}
You can add ?
(question mark) after a property/variable name. It is to mark the property/variable as optional.
class Example {
doSomething(): void {
const username = 'David' as string | undefined;
// add ? (question mark) after the property/variable,
// the error gone away! :)
const length = username?.length;
}
}
developer.mozilla - Оператор опциональной последовательности