【问题标题】:Remove | null from Typescript type删除 |来自 Typescript 类型的 null
【发布时间】:2018-01-07 16:34:58
【问题描述】:

我刚开始学习 TypeScript,在某些情况下,我得到的可能是 Type 或 null。有没有优雅的方法来处理这些情况?

function useHTMLElement(item: HTMLElement) {
  console.log("it worked!")
}

let myCanvas = document.getElementById('point_file');
if (myCanvas == null) {
  // abort or do something to make it non-null
}
// now I know myCanvas is not null. But the type is still `HTMLElement | null`
// I want to pass it to functions that only accept HTMLElement.
// is there a good way to tell TypeScript that it's not null anymore?
useHTMLElement(myCanvas);

我编写了以下似乎可行的函数,但这似乎是一种常见的情况,我想知道语言本身是否为此提供了一些东西。

function ensureNonNull <T> (item: T | null) : T {
  if (item == null) {
    throw new Error("It's dead Jim!")
  }
  // cast it
  return <T> item;
}
useHTMLElement(ensureNonNull(myCanvas));

【问题讨论】:

    标签: javascript typescript types error-handling null


    【解决方案1】:

    如果您实际上if 块中执行某些操作以使 myCanvasnull,TypeScript 将识别:

    let myCanvas = document.getElementById('point_fiel');
    if (myCanvas == null) {
        return; // or throw, etc.
    }
    useHTMLElement(myCanvas); // OK
    

    let myCanvas = document.getElementById('point_fiel');
    if (myCanvas == null) {
        myCanvas = document.createElement('canvas');
    }
    useHTMLElement(myCanvas); // OK
    

    【讨论】:

      【解决方案2】:

      Typescript 类型保护也可以识别 instanceof 运算符 - 当您不需要知道 not-null 时很有用

      let myCanvas = document.getElementById('point_fiel');
      if (myCanvas instanceof HTMLCanvasElement) {
        useHTMLElement(myCanvas);
      } else if (myCanvas instanceof HTMLElement) {
        // was expecting a Canvas but got something else
        // take appropriate action 
      } else {
        // no element found 
      }
      

      【讨论】:

        猜你喜欢
        • 2014-03-23
        • 2022-09-28
        • 2022-01-05
        • 2019-04-26
        • 1970-01-01
        • 2020-05-30
        • 1970-01-01
        • 2018-03-27
        • 2021-11-06
        相关资源
        最近更新 更多