2017-08-01 151 views
1

我剛開始學習TypeScript,在某些情況下,我得到的可能是Type或null。有沒有一種優雅的方式來處理這些案件?刪除| null Typescript type

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

回答

1

如果實際上做一些事情在if塊,使myCanvasnull,打字稿會認識到:

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 
+0

完美,謝謝! – Ben

1

打字稿typeguards也認識到instanceof操作符 - 非空時有用並不是你所需要知道的

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