Typescript 为什么字体防护装置不缩小字体?
我有一些使用类型保护函数的代码:Typescript 为什么字体防护装置不缩小字体?,typescript,typeguards,type-narrowing,Typescript,Typeguards,Type Narrowing,我有一些使用类型保护函数的代码: 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
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;
}
类型脚本报告:
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的评论是正确的:将测试结果保存在变量中,然后在变量上进行分支不会执行收缩。以下是。我认为类型缩小不会在布尔变量之间传播。
if (!save_sig_check || !assertInstanceOf(save_sig_check, HTMLInputElement)) {
return true;
}
if (save_sig_check.checked) {
this.saveSignatureData(name, output);
}