Typescript: Object Is Possibly 'Undefined'

How can I solve the error 'TS2532: Object is possibly 'undefined'?

error 'TS2532: Object is possibly 'undefined'

"Object is possibly undefined" when that is not possible

This has less to do with the order and rather with the fact you are using a narrowing if statement which allows TS to infer this properly. IE, it will work in this order as well.

.filter(([k, v]) => v !== undefined)
.map(([k, v]) => {
if (v === undefined) {
return [k, v]
} else {
return [k, v.toString()]

Filter assumes its return value to always match the same shape as its predicate, this is just simply a limitation of how it was typed. TS can not evaluate compile-code across scope-boundaries very well. Nor does it try to, for various reasons, IIRC there are many cases in which a module may be augmented (thus changing the implementation), alternatively you can augment (and/or overload) the declaration yourself if you prefer to. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation, OR to declare a different type only syntax here, ie. declare global {...}, using your own type generics to describe the return value.

But there is not much point to, since it will be equally as verbose as the answer below

You can cast it using as

.filter(([k, v]) => v !== undefined) as [string, string][])
.map(([k, v]) => [k, v.toString()])

View this on TS Playground

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This feature is called "strict null checks", to turn it off ensure that the --strictNullChecks compiler flag is not set.

However, the existence of null has been described as The Billion Dollar Mistake, so it is exciting to see languages such as TypeScript introducing a fix. I'd strongly recommend keeping it turned on.

One way to fix this is to ensure that the values are never null or undefined, for example by initialising them up front:

interface SelectProtected {
readonly wrapperElement: HTMLDivElement;
readonly inputElement: HTMLInputElement;

const selectProtected: SelectProtected = {
wrapperElement: document.createElement("div"),
inputElement: document.createElement("input")

See Ryan Cavanaugh's answer for an alternative option, though!

How to solve TS2532 Object is possibly 'undefined'. with an Array?

Do this:


Related Topics

Leave a reply