流类型 - 将 HTMLElement 转换为 HTMLInputElement

Flow types - Casting HTMLElement to HTMLInputElement

我有以下代码:

const metricsInputEl = document.querySelector(
  'input[name="metrics"]',
);

const value = metricsInputEl.value;

但我收到以下流程错误:

Cannot get metricsInputEl.value because:
 • property value is missing in HTMLElement [1].

如何解决这个问题?

以下有效,但我不太喜欢它,因为 instanceof 检查不会被删除,我不希望它成为我的包的一部分并在运行时进行冗余类型检查。

const metricsInputEl = document.querySelector(
  'input[name="metrics"]',
);

if (metricsInputEl instanceof HTMLInputElement) {
  const value = metricsInputEl.value;
}

我认为您可以利用 Flow 的 Comment Types。您可以在 Flow 注释中执行 instanceof 检查,这将满足 Flow 的类型系统,但应该被转译器删除。

const metricsInputEl = document.querySelector(
  'input[name="metrics"]',
);


/*::
if (!(metricsInputEl instanceof HTMLInputElement)) {
  throw new Error('element is not of type HTMLInputElement');
}
*/

const value = metricsInputEl.value;

请注意,这可能很危险,因为具有 name="metrics" 的元素不能保证是 HTMLInputElement,但如果您确信这将始终为真,那么它可能是一个很好的选择满足 Flow 的方法。