gpt4 book ai didi

javascript - 删除 |来自 Typescript 类型的 null

转载 作者:搜寻专家 更新时间:2023-10-30 20:57:28 25 4
gpt4 key购买 nike

我刚开始学习 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));

最佳答案

如果您实际上if block 中做一些事情来使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

关于javascript - 删除 |来自 Typescript 类型的 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45427155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com