2

I want to simply extend the standard javascript Error class. I want to add another property: code, but somehow, the typescript don't let me do it.

export class HttpError extends Error {
    public message: string
    public errorCode: number
    constructor(message: string, errorCode: number) {
        super(message) // Add a
        (this as any).code = errorCode
    }
}

The typescript error is at the super(message):

This expression is not callable.
Type 'void' has no call signatures.ts(2349)

However, in typescript documentation: https://www.typescriptlang.org/docs/handbook/classes.html they also do the same way.

What's wrong with my code?

xirururu
  • 3,852
  • 6
  • 28
  • 48

2 Answers2

5

This is, in my subjective opinion, a good example of why omitting semicolons is not a good practice. While Javascript supports automatic semicolon insertion, it can often lead to unexpected bugs like this.

Reformatting your code as the compiler sees it, the error becomes apparent:

constructor(message: string, errorCode: number) {
    super(message)(this as any).code = errorCode
}

If you add semicolons where they're supposed to be, the problem goes away.

Etheryte
  • 20,940
  • 10
  • 58
  • 98
1

just add ; to the super call

constructor(message: string, errorCode: number) {
    super(message); // Add a
    (this as any).code = errorCode
}

honestly, I can't understand why this issues an error but I copied your code to my editor and added ; to the super call and the error went away

Ali Faris
  • 13,532
  • 6
  • 31
  • 54