'How to use `typeof` for derived classes to check with `instanceof`

This is my use-case:

class Error1 extends Error {
    constructor(somethingDifferent: number) {
        super('anything!');
    }
}

class Error2 extends Error {
    constructor(hellYeah: string[]) {
        super('woho!');
    }
}

type ErrorToHandler = {
    handler: Function;
    errorType: typeof Error; // HOW TO EXTEND this to be able to handle all types of erorrs extending an Error
}

function fnWhichTakesAnyError(err: Error) {
    console.log('DO SOMETHING!');
}

fnWhichTakesAnyError(new Error1(1)); // works without any problem
fnWhichTakesAnyError(new Error2(['2'])); // works without any problem too

const errorHandlers: ErrorToHandler[] = [
    {
        errorType: Error,
        handler: () => { }
    },
    {
        errorType: Error1, // here comes an error, see below
        handler: () => { }
    }
]

function handleError(error: unknown) {
    errorHandlers.find(eh => error instanceof eh.errorType)?.handler();
}

The error message:

Type 'typeof Error1' is not assignable to type 'ErrorConstructor'.

Type 'typeof Error1' provides no match for the signature '(message?: string | undefined): Error'.(2322)

input.tsx(15, 5): The expected type comes from property 'errorType' which is declared here on type 'ErrorToHandler'

if it's not possible to get this working with extended types, is there a way to just put in any type which could be checked by instanceof?

Playground



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source