Home > other >  How to tell TypeScript that an error from a `try catch` statement is an object that contains a speci
How to tell TypeScript that an error from a `try catch` statement is an object that contains a speci

Time:07-04

I get an error in the console.log statement below:

try {
    // ...
} catch(e) {
    if (typeof e === "object" && e !== null && e.hasOwnProperty("data")) {
        console.log(e.data);
    }
}

when I try to access e.data, I get the following TypeScript error:

Property 'data' does not exist on type 'object'.ts(2339)

I explicitly check if e has a property of data though right? So I'm not understanding why TypeScript is saying data doesn't exist on e.

How can I tell TypeScript properly that e has a property of data? I know I can cast the error as an any type, but I don't think this is good practice and would like to refrain from using any if possible. My work does not allow for casting any anywhere in the codebase.

screenshots of my errors below:

e is of unknown

typescript error

CodePudding user response:

You can use a predicate !

try {
    // ...
} catch (e) {
    if (hasData(e)) {
        console.log(e.data);
    }
}

function hasData(object: unknown): object is { data: unknown } {
    return (typeof object === "object" && object?.hasOwnProperty("data")) ?? false
}

[Playground][2]

CodePudding user response:

There are a lot of ways you could fix this, depending what you're going for.

But this is the simplest:

try {
    // ...
} catch(e: any) {
    if (typeof e === "object" && e !== null && e.data) {
        console.log(e.data);
    }
}

Note that TypeScript has limitations surrounding what you can do in terms of type specification in a catch clause, so you can't do something more complicated like declare an error type containing a data property or anything.

Here's the above code in a TypeScript playground.

  • Related