Assuming the compiler option strictNullChecks
is enabled.
Imagine having a function that returns either a :string|undefined
, and another function that specifically requires a :string
. In such a scenario, how can you handle calling the second function or converting :string|undefined
to simply :string
?
Consider the following code snippet as an example:
function alpha(): string|undefined {
return "hello";
}
function beta(s: string) {
console.log(s);
}
function isEmpty(s: string|undefined): boolean {
if (s === undefined) {
return true;
} else if (s.trim().length === 0) {
return true;
}
return false;
}
const s = alpha();
if (isEmpty(s)) {
throw new Error("I have manually ensured it's not undefined.");
}
beta(s);
This would lead to the error message:
Error:(22, 6) TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.