首页 > 解决方案 > 从 javascript/typescript 中的类返回错误

问题描述

假设我有一个这样的界面:

class Something {
    constructor(things) {
        if (things) {
            doSomething();
        } else return { errorCode: 1 }
    }
}

这段代码可以吗?在 TypeScript 中,我收到类似于property errorCode does not exist on type Something. 有什么替代方法可以做到这一点?这是我想到的:

class Something {
    constructor(things) {
        if (things) {
            doSomething();
        } else this.error = { errorCode: 1 }
    }
}

它们都具有相同的效果。但我想知道哪种方法更好。

标签: javascripttypescriptclass

解决方案


因此,将错误定义为类的一部分

interface MyError {
  errorCode: number;
}

class Something {
    private error: MyError;
    constructor(things) {
        if (things) {
            doSomething();
        } else this.error = { errorCode: 1 }
    }
}

推荐阅读