typescript - 为什么类型保护不会缩小类型?
问题描述
我有一些使用类型保护功能的代码:
function assertInstanceOf<T>(
value: any,
expected_type: new(...args: any[]) => T,
): value is T {
if (value instanceof expected_type) { return true; }
notify(`value '${value}' was not expected type '${expected_type.name}'`);
return false;
}
在以下场景中,类型保护似乎没有坚持:
const save_sig_check = $modal.find('#save_signature')[0];
const is_html_input_element =
save_sig_check && assertInstanceOf(save_sig_check, HTMLInputElement);
if (is_html_input_element && save_sig_check.checked) {
this.saveSignatureData(name, output);
}
打字稿报告:
error TS2339: Property 'checked' does not exist on type 'HTMLElement'.
113 if (is_html_input_element && save_sig_check.checked) {
~~~~~~~
但是,如果我像这样重新排列代码,TypeScript 不会抱怨:
if (!save_sig_check || !assertInstanceOf(save_sig_check, HTMLInputElement)) {
return true;
}
if (save_sig_check.checked) {
this.saveSignatureData(name, output);
}
这第二个对我来说有点难以阅读,所以想知道为什么第一个不起作用。有任何想法吗?仍在使用 TypeScript 2.8.3。
解决方案
SLaks 的评论是正确的:将测试结果保存在变量中,然后在变量上进行分支不会执行缩小。这是建议。
推荐阅读
- tree - Prolog 中的树
- java - Install4j - 如何在 UI 表单中添加组框
- php - 在mysql php中得到真假结果
- vue.js - 在 Vue 子组件中提取道具中的信息
- html - SVG:如何在元素内均匀地居中多行文本?
- c - C - 在阅读 CTRL+Z 之前如何阅读短语?
- javascript - 检测您的网页是否在应用程序的 WebView 中查看?
- fortran - Fortran 编译器指示无效表达式
- azure-devops - 如何通过 Azure Devops 将 UWP 包发布到 Windows 应用商店?
- ios - Unity Cloud Build iOS 错误 Undefined symbols for architecture armv7