Home > Software engineering >  Typescript number or object. Property on object doesn't exist
Typescript number or object. Property on object doesn't exist

Time:11-23

I'm trying to understand why this is invalid but googling hasn't lead me to any answers so I'm hoping somebody can point me in the right direction here.

const latestTotal: number | {
    x: any;
    y: any;
    fillColor?: string | undefined;
    strokeColor?: string | undefined;
    meta?: any;
    goals?: any;
} | [number, number | null] | [number, (number | null)[]] | null | undefined

console.log(latestTotal.y)
// Property 'y' does not exist on type 'number | { x: any; y: any; fillColor?: string | undefined; strokeColor?: string | undefined; meta?: any; goals?: any; } | [number, number | null] | [number, (number | null)[]]'. Property 'y' does not exist on type 'number'

Shouldn't it look at the object definition instead of the number definition? This def is from a library so I can't change it. Can anybody paint me a picture here?

CodePudding user response:

This is because number | {...} means that the variable can be both number or object and as .y does not exist on number you are getting this error.

This behavior is explained here in official documentation: wrong way

Correct Way correct way

  • Related