删除|从Typescript类型返回null

时间:2017-08-01 00:23:07

标签: javascript typescript types error-handling null

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

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

let myCanvas = document.getElementById('point_fiel');
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));

2 个答案:

答案 0 :(得分:2)

如果您实际if区块中执行某项操作以使myCanvas非 - null,则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

答案 1 :(得分:2)

Typescript typeguards也识别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 
}