0

我有一些使用类型保护功能的代码:

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。

4

1 回答 1

0

SLaks 的评论是正确的:将测试结果保存在变量中,然后在变量上进行分支不会执行缩小。这是建议

于 2018-09-06T03:30:40.503 回答