I am building a utility function that will catch instances of given error classes and return them, tracking the types based on the given error classes.
The issue that I am running into is that I cannot maintain the specificity of built-in errors. For example InstanceType<typeof TypeError>
will lead to Error
but I want it to kept as TypeError
. I looked into the TS lib types to better understand. In TS those built-in Error classes are actually just defined as interfaces like interface TypeError extends Error {}
with a separate type definition for constructors e.g. TypeErrorConstructor
. Given this, is it possible with these type definitions as they are to achieve what I want? Perhaps one has to augment the global types with improved definitions that use class TypeError extends Error
? But that significantly complicates the simple utility I am trying to build.
Is there a way for this generic utility function:
declare const catchInstanceOfErrors:
<errorClass extends typeof Error | typeof DOMException>(errorClasses: errorClass[]) =>
((value: unknown) => InstanceType<errorClass>)
to infer a TypeError
instance given a TypeError class?
const error = catchInstanceOfErrors([TypeError])(new TypeError())
Here is a TS playground of this utility with a failing test.