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

javascript - Typescript: 'new' expression, whose target lacks a construct signature, implicitly has an '

programmeradmin2浏览0评论

The following is the code that works best for displaying custom errors in Chrome Devtools, Node.js, etc. Based on this StackOverflow answer.

function CustomErr (message) {
  var err = new Error(message)
  Object.setPrototypeOf(err, CustomErr.prototype)
  return err
}

CustomErr.prototype = Object.create(Error.prototype, {
  name: { value: 'Custom Error', enumerable: false }
})

However, when I convert it to Typescript:

function CustomErr (message: string) {
  var err = new Error(message)
  Object.setPrototypeOf(err, CustomErr.prototype)
  return err
}

CustomErr.prototype = Object.create(Error.prototype, {
  name: { value: 'Custom Error', enumerable: false }
})

Calling throw new CustomErr("something went wrong") shows this error:

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)

What can I do to correctly type-annotate my code? If you can find another equivalent code solution, feel free to suggest it, but it MUST have the same behavior in Chrome DevTools (this alone of all solutions I tried displays a custom error name nicely). Thanks!

EDIT: Need to support older browsers, so I can't use ES6 classes. I'd prefer not to transpile classes to ES6 because I'm creating a lightweight library, and a class polyfill alone is 10% of my entire codesize.

So to recap, how can I annotate the code I have now?

The following is the code that works best for displaying custom errors in Chrome Devtools, Node.js, etc. Based on this StackOverflow answer.

function CustomErr (message) {
  var err = new Error(message)
  Object.setPrototypeOf(err, CustomErr.prototype)
  return err
}

CustomErr.prototype = Object.create(Error.prototype, {
  name: { value: 'Custom Error', enumerable: false }
})

However, when I convert it to Typescript:

function CustomErr (message: string) {
  var err = new Error(message)
  Object.setPrototypeOf(err, CustomErr.prototype)
  return err
}

CustomErr.prototype = Object.create(Error.prototype, {
  name: { value: 'Custom Error', enumerable: false }
})

Calling throw new CustomErr("something went wrong") shows this error:

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)

What can I do to correctly type-annotate my code? If you can find another equivalent code solution, feel free to suggest it, but it MUST have the same behavior in Chrome DevTools (this alone of all solutions I tried displays a custom error name nicely). Thanks!

EDIT: Need to support older browsers, so I can't use ES6 classes. I'd prefer not to transpile classes to ES6 because I'm creating a lightweight library, and a class polyfill alone is 10% of my entire codesize.

So to recap, how can I annotate the code I have now?

Share Improve this question edited Dec 20, 2019 at 14:30 Ben Gubler asked Dec 20, 2019 at 5:20 Ben GublerBen Gubler 1,4414 gold badges20 silver badges34 bronze badges 3
  • Are you getting this error at compile time? – Sohan Commented Dec 20, 2019 at 5:37
  • you have to compile (or at least traspile) typescript, what do you mean by not to transpile... you wouldnt be able to run typescript without it. – Juraj Kocan Commented Dec 20, 2019 at 8:12
  • If you do want a lightweight ES5 library, you may really want to consider writing a lightweight ES5 library and do not touch TypeScript in the process. And vice versa: if you write TypeScript, let the tools worry about JavaScript. – tevemadar Commented Dec 20, 2019 at 14:44
Add a comment  | 

3 Answers 3

Reset to default 14

You can declare class, but implement it with a function. This way output (the resulting javascript) won't be affected, but typescript will treat the CustomErr as a "newable":

declare class CustomErr extends Error {
    constructor(message: string);
}

function CustomErr(message: string) {
    var err = new Error(message)
    Object.setPrototypeOf(err, CustomErr.prototype)
    return err
}

CustomErr.prototype = Object.create(Error.prototype, {
    name: { value: 'Custom Error', enumerable: false }
})

throw new CustomErr("something went wrong") // no error now

Playground

I was able to implement custom errors in TypeScript by doing

interface Exception {
    code: number;
    message: string;
}

export const Exception = (function (this: Exception, code: number, message: string) {
    this.code = code;
    this.message = message;
} as unknown) as { new (code: number, message: string): Exception };

Then I can use it anywhere in my codebase like

throw new Exception(403, 'A custom error');

Or in an async operation

export const CreateUser = async ({ email, password }: { email: string; password: string }): Promise<IUser> => {
    try {
        // some async operations

        throw new Exception(403, 'Error creating user');
    } catch (error) {
        return Promise.reject(error);
    }
};

I still have no idea how to annotate my code, but just changing throw new CustomErr('err') to throw CustomErr('err') fixed my problem. Though JS allows you to use the new constructor, TypeScript doesn't.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论