我想创建一个函数,检查变量是不是null
或undefined
。
我想要的是检查后的安全类型的变量。
在我的上一个项目中,我做了以下工作:
function isDefined<T>(value: T): value is T {
return <T>value !== undefined && <T>value !== null;
}
但是为什么它在我当前的项目中不起作用,可能是由于不同的tsconfig - 我可以在isDefined(foo)
(项目使用相同的打字稿版本 - "2.7.2"
)之后看到许多错误,例如“变量可能为空”
我还看到了另一种方法,它是有效的,但......在术语或类型方面有点奇怪。
function isDefined(value: any): value is {} | string | number | boolean {
return value !== undefined && value !== null;
}
问题:如何创建可以保存变量类型的isDefined
?
UPD1:用法示例:
const foo:string | undefined ='foo';
function getFoo(foo: String): void {
console.log(foo);
}
function getBar(foo: string | undefined) {
if (isDefined(foo)) {
getFoo(foo); // getFoo still think that foo maight be undefined
}
}
export function isDefined<T>(value: T): value is T {
return <T>value !== undefined && <T>value !== null;
}
好的,我发现该解决方案有效并且类型友好:
tl;博士
function isDefined<T>(value: T | undefined | null): value is T {
return <T>value !== undefined && <T>value !== null;
}
为什么?
这样,isDefined()
将尊重变量的类型,以下代码将知道这个检查帐户。
示例1 - basik检查:
function getFoo(foo: string): void {
//
}
function getBar(bar: string| undefined) {
getFoo(bar); //ERROR: "bar" can be undefined
if (isDefined(bar)) {
getFoo(bar); // Ok now, typescript knows that "bar' is defined
}
}
示例2 - 类型方面:
function getFoo(foo: string): void {
//
}
function getBar(bar: number | undefined) {
getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
if (isDefined(bar)) {
getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
}
}