javascript - 从 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 }
}
}
它们都具有相同的效果。但我想知道哪种方法更好。
解决方案
因此,将错误定义为类的一部分
interface MyError {
errorCode: number;
}
class Something {
private error: MyError;
constructor(things) {
if (things) {
doSomething();
} else this.error = { errorCode: 1 }
}
}
推荐阅读
- ms-word - 有没有办法从命令行或 python 使用 Microsoft Word Save as -> html?
- angular - Angular 项目中没有智能感知的 Visual Studio 代码
- c - Malloc 调用系统调用
- reactjs - React.js:未处理的拒绝(TypeError):无法读取未定义的属性“错误”
- javascript - UI 组件内的@Input 变量返回 null
- ios - 当我从网站启动应用程序时,我的分支 io 链接未在应用程序中打开
- ckeditor - CKEditor 5 - v 19.0.0 下划线功能不起作用
- github - 特定版本私有包的 NPM 依赖
- django - DRF:仅用于代表目的。如何组合两个序列化器
- c# - ITextSharp 在标题中添加徽标以及文本