最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - How to infer error instance from built-in error classes like TypeError - Stack Overflow

programmeradmin3浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论