Typescript is an object-oriented language, which was designed by Microsoft. It is a superset of JavaScript. If you are attempting to execute the command but received the error “Object is possibly ‘undefined’”. We will show you how to fix it here, in this post.
What is “Object is possibly ‘undefined’” error?
To help you easily realize that you are facing the above error, we have the following example:
Suppose you need to declare a function as follows:
if (a && a[k])
However, the result returned for a[k].toString().toLowerCase()
after you declared it was undefined (or “null”). Specifically, you may see the above error being displayed as follows:
// Return coins that match text search by currency symbol or name.
export const findAsset = (txt: string, assets: IAsset[] | null[]) => {
// assets will exist here...
if (assets) {
// Typescript error here...
const checkText = (k: string, a: IAsset | null) => {
if (a && a[k]) {
return (textMatch(txt.toLowerCase(), a[k].toString().toLowerCase()) ? a : null);
}
}
// Do something
}
else {
return [];
}
};
In addition, if you are using the IAsset
interface, you can identify the above error similar to the program below:
export interface IAsset {
[key: string]: string | number | undefined | boolean;
availableSupply?: string;
currency: string;
exchange: string;
exchange_base?: string;
marketCap: number;
name: string;
percentage?: number;
price: number;
position?: number;
value?: number;
inWatchlist?: boolean;
}
and this will be the display of the error when you use tsconfig
{
"compilerOptions": {
/* Basic Options */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": [
"dom",
"es2015",
"es2016",
"es2017",
], /* Specify library files to be included in the compilation. */,
"allowJs": true, /* Allow javascript files to be compiled. */
"checkJs": true, /* Report errors in .js files. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
"noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
"resolveJsonModule": true,
"downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true /* Enable strict null checks. */,
"strictFunctionTypes": true /* Enable strict checking of function types. */,
"strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
"strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
"noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
"alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
},
"include": [
"components/**/*",
"pages/**/*",
],
"exclude": [
"node_modules",
"styles",
"_document.tsx"
]
}
What causes error?
The error is caused by the property of an object could result in a null or undefined. It is a compile-time error for an object possible is null after setting -strictNullChecks=true compiler configuration flag.
For instance, in the following code, str is defined using string array, null or undefined. str property could be null or undefined value.
let str: string[] | undefined|null
let len: number = str.length; // Object is possibly 'null' or 'undefined'.
In the code line above (str. length) in the above code line, accessing the length of the string object results in this error The object could be undefined or null during compile time and also linting is set.
How To Solve The Problem?
Luckily for you, if you encounter this error “Object is possibly ‘undefined’ in Typescript”, don’t worry, there are quite a few ways to fix it. Here are some solutions we have summarized, please refer to and choose the right one for you.
Suggestion 1: Fix the problem using an Optional Chaining Operator
Using Non-null assertion operator symbol, and then added to the variable in order to avoid non-null or undefined.
In this case, to solve this error, the program must be received the correct value type. You can add the (||) operator as a fallback in the command below:
a[k].toString().toLowerCase()
replace with :
(a[k] || '').toString().toLowerCase()
// Or with optional chaining
a[k]?.toString().toLowerCase() || ''
Suggestion 2: Assign to a new variable
In addition, you can save the value to a variable and check the new one.
For example, in this case you can assign v = a ? a[k] : null
and check it, speciclly:
Change this command:
if (a && a[k]) {
return textMatch(txt.toLowerCase(), a[k].toString().toLowerCase()) ? a : null;
}
Become:
let v = a ? a[k] : null
if (v) {
return textMatch(txt.toLowerCase(), v.toString().toLowerCase()) ? a : null;
}
Suggestion 3: Using checktext
Another way you can use checktext with optional chaining operator, to make sure, firstly, install the stable version of TypeScript (using npm install typescript
), then apply the following code:
const checkText = (k: string, a: IAsset | null) => {
return (textMatch(txt.toLowerCase(), a?.[k].toString().toLowerCase()) ? a : null);
}
Conclusion
Those are suggestions for the error in TypeScript: Object is possibly ‘undefined’. We hope you enjoyed our post. If you’re experiencing this error, don’t worry! It’s a simple fix!
If you could not find the error being discussed in the post, don’t hesitate to get in touch with our team so that we can help you resolve the issue! Please leave your ideas and questions in the comments section below and know which approach worked best for you. Thank you!
Just add some options here for your reference
In this option, that is call the object
And, another option
Have you tried these method? Or tell me which one is the best by leave your message below so that I can share to others in the IT community.
Thank for reading and Have a nice day!
Thanks, this is a helpful post. I fixed the same problem by referencing this post