Search code examples
typescripttypestry-catch

How to tell TypeScript that an error from a `try catch` statement is an object that contains a specific property without using the `any` type?


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


Solution

  • 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]