David Gomes
David Gomes

Reputation: 5815

Distinguish between two similar objects

I have this piece of code:

interface MysqlError extends Error {
    /**
     * Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'),
     * a node.js error (e.g. 'ECONNREFUSED') or an internal error
     * (e.g. 'PROTOCOL_CONNECTION_LOST').
     */
    code: string;
}

function f(err: Error | MysqlError) {
    if (err.code) {
    } else {
    }
}

But I get the following error:

Property 'code' does not exist on type 'MysqlError | Error'.
  Property 'code' does not exist on type 'Error'.

How can I check which type I got in this function?

TypeScript Playground Link

Upvotes: 0

Views: 54

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

I would use an in type-guard in this case to test for the existence of the code property:

interface MysqlError extends Error {
    code: string;
}

function f(err: Error | MysqlError) {

    if ('code' in err) {
        err.code // string
    } else {

    }
}

Upvotes: 3

Related Questions