How to declare a function that throws an error in Typescript

后端 未结 4 920
孤独总比滥情好
孤独总比滥情好 2020-12-18 18:00

In Java I would declare a function like this:

public boolean Test(boolean test) throws Exception {
  if (test == true)
    return false;
  throw new Excepti         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 18:11

    You could treat JavaScript's Error as Java's RuntimeException (unchecked exception). You can extend JavaScript's Error but you have to use Object.setPrototypeOf to restore the prototype chain because Error breaks it. The need for setPrototypeOf is explained in this answer too.

    export class AppError extends Error {
        code: string;
    
        constructor(message?: string, code?: string) {
            super(message);  // 'Error' breaks prototype chain here
            Object.setPrototypeOf(this, new.target.prototype);  // restore prototype chain
            this.name = 'AppError';
            this.code = code;
        }
    }
    
    

提交回复
热议问题