Sergey Korenyuk
Sergey Korenyuk

Reputation: 33

How to solve the error TS2532: Object is possibly 'undefined'

I have code where I should check complicated condition several times. F.E: (a && b) || c, etc. I tried to add variable with my condition like const hasSomething = (a && b) || c, and I faced with issue with TS which I can't solve.

Example Works:

function add(a?: number, b?: number): number {

    if (a && b) {
        return a + b;
    }
    return 0;
}

Doesn't work:

function add(a?: number, b?: number): number {
    const hasNumbers = a && b;

    if (hasNumbers) {
        return a + b;
               ^   ^
               TS2532: Object is possibly 'undefined'.
    }
    return 0;
}

Is is any workaround to fix it without non-null assertion !?

Upvotes: 2

Views: 777

Answers (2)

InsalataCondita
InsalataCondita

Reputation: 351

the && (and) operator with number doesn't work as expected:

if you use it like this:

const foo = 3 && 4

you can see that the typeof foo is "number".

In fact the && operators returns:

  • the last number if the result will be true, example: 5 && 4 is true so it will return 4

  • the falsy value is there is one: example 0 && 4 has 0 as false value and will return 0, same with undefined && 4 this will return undefined

TypeScript versions lower than 4.4.0 will not truly understand which will be the real result due to the fact that it could be undefined AFAIK.

that said is also a bad practice using number && number when at least one of the two values can be 0 due to the fact that 0 is a falsy value and in your function any sum with 0 in it will result in a 0 response according to the a && b check.

I suggest you to just make the function parameters mandatory in order to avoid the error and avoid the hasNumbers check:

function add(a: number, b: number): number {

    return a + b
}

Upvotes: 1

Easy to fix :D. Just update the version of TypeScript to 4.4:

function add(a?: number, b?: number): number {
    const hasNumbers = a && b;
    if (hasNumbers) {
        return a + b;
    }
    return 0;
}

Playground

Upvotes: 1

Related Questions