【问题标题】:Why a type guard does not narrow a type?为什么类型保护不会缩小类型?
【发布时间】:2018-09-06 01:29:14
【问题描述】:

我有一些使用类型保护函数的代码:

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);
}

TypeScript 报告:

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。

【问题讨论】:

  • 我认为类型缩小不会跨布尔变量传播。

标签: typescript typeguards type-narrowing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多