我有一个我想用来管理Checkbox的TypeScript类。它看起来像这样:
export class TriStateCheckboxManager {
constructor(public checkBox: HTMLInputElement) {
if (checkBox.type != "checkbox") {
// What now?
}
}
}
如果复选框的类型不等于checkbox
,我如何引发错误。
答案 0 :(得分:4)
因为TypeScript是JavaScript的超集,所以它支持所有内置的JavaScript函数,类型,对象,关键字等。您要查找的是 throw
关键字,它会引发所需的异常。
到目前为止,您的代码很好,因此以下内容可以胜任。
export class TriStateCheckboxManager {
constructor(public checkBox: HTMLInputElement) {
if (checkBox.type !== "checkbox") {
// checkBox doesn't meet the reqruirements,
// so raise an error. Optionally, you could
// log a message, warning or whatever you want
// to the console.
console.warn("checkBox.type doesn't match.", checkBox, this);
throw "checkBox.type doesn't match." // Throw anything you want here
}
}
}
顺便说一句:强烈建议您使用!==
和===
进行JavaScript(因此是TypeScript)而不是!=
和==
的比较。有关详情,请参阅here。
编辑: 正如MiMo在下面所说,你可以抛出你想要的任何类型,所以一个对象也是一个合适的候选者。
我发现this文章看起来很有前途,如果您正在进行JavaScript / TypeScript错误处理。这是用于在JavaScript中抛出错误的MDN页面。