2017-08-01 89 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 
}