TypeScript isNullOrUndefined
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41955762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:13:20 来源:igfitidea点击:
TypeScript isNullOrUndefined
提问by NN_
How I type such function ?
我如何输入这样的函数?
function isNullOrUndefined(obj: any) {
return typeof obj === "undefined" || obj === null;
}
If I return any it means it can be still null or undefined. I want to use it this way:
如果我返回任何它意味着它仍然可以为空或未定义。我想这样使用它:
let a: string | null | undefined = undefined;
if (!isNullOrUndefined(a)) {
const b: string = a;
}
回答by NN_
Found !
成立 !
function isNullOrUndefined<T>(obj: T | null | undefined): obj is null | undefined {
return typeof obj === "undefined" || obj === null;
}
回答by Jakub Synowiec
You can use the optional - ?:
parameter declaration and take the advantage of loose equality (coercion)between null
and undefined
to simplify this function:
您可以使用可选的-?:
参数声明,并采取优势宽松平等的(胁迫)之间null
,并undefined
简化了这个功能:
function isNullOrUndefined<T>(obj?: T | null): boolean {
// null == undefined so this is true if obj = null or obj = undefined
return obj == null;
}