#Behavior of `is TypeError` type guard

7 messages · Page 1 of 1 (latest)

alpine citrus
#

typescript playground: https://www.typescriptlang.org/play/?#code/DYUwLgBCBO0PbQFwQK4DsDWa4Hc0Ch8ATEAY2AENoQIAzdUsASzjQiYGcAVATwAcQAUVgIAFADcKwFCGTosuNAEpkk6TU4ReA4fGiEmtCKM7ahI6KJh6lSiAG98EZ1AtOXAeg8QAegH53Z0CIMAALeBwINBBI3TElfABfQmsEfC9fAPxDY1TodjQOMAo0UhA4IzjoO0cXVz1gjP9COpyTbn5zPSsLWwdguoyAdVCedg4Q0M0qiBKiKLhIMyqAurq8gc9vZs3nMIiomIgq0QS65OCNwe2A5KA

in the following code snippet, why is the behavior of the isTypeError type guard different, depending on whether the block is wrapped in an instanceof Error check or not - on line 6 error is narrowed to TypeError, and consequently on line 12, error is unknown - but on line 21, error is narrowed to Error and consequently error on line 27 is never (i had expected it to still be Error)

let error: unknown

declare function isTypeError(value: unknown): value is TypeError

if (isTypeError(error)) {
    error
    // ^?
    
    throw new Error()
}

error
// ^?

if (error instanceof Error) {
    error
    // ^?

    if (isTypeError(error)) {
        // Why is this Error and not TypeError?
        error
        // ^?

        throw new Error()
    }

    error
    // ^?
}
wary stormBOT
#

@alpine citrus Here's a shortened URL of your playground link! You can remove the full link from your message.

spbks#0

Preview:```ts
let error: unknown

declare function isTypeError(
value: unknown
): value is TypeError

if (isTypeError(error)) {
error
// ^?

throw new Error()
}

error
// ^?

if (error instanceof Error) {
error
// ^?

if (isTypeError(error)) {
// Why is this Error
...```

alpine citrus
zinc hatchBOT
#
export default function isNetworkError(value: unknown): value is TypeError;
proven crest
#

TypeError is defined as:

interface TypeError extends Error {
}

So it's structurally identical to Error.

clear stone
#

yeah, the difference you observe is only in the type info. this might help clarify

alpine citrus
#

ah thanks! that makes sense!