I want to create function that checks if variable is not null
or undefined
.
What I want is to safe type of variable after the check.
In my last project I did it following:
function isDefined<T>(value: T): value is T {
return <T>value !== undefined && <T>value !== null;
}
But somewhy it doesn't work in my current project, perhaps due to different tsconfig - I can see a number of errors like "variable might be null" after isDefined(foo)
(projects are use same typescript versions - "2.7.2"
)
I also saw another approach, which is works, but... a bit weird in terms or types.
function isDefined(value: any): value is {} | string | number | boolean {
return value !== undefined && value !== null;
}
Question: How to create isDefined
that would save type of the variable?
UPD1: Example of usage:
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;
}