Reputation: 1
const x = (): string | number => {
return 'hola';
}
const n = (x: string): string => {
return x;
}
n(x())
When writing this code I am receiving a compiling error within the n(x()) that says that type string | number cannot be assigned to type string. Any idea why? Thank you!
Upvotes: 0
Views: 41
Reputation: 250176
Since x
can return either a string
or a number
it's not safe to pass the result to n
which expects a string
. Consider the following code:
const x = (): string | number => {
return Math.random() > 0.5 ? 'hola' : 0;
}
const n = (x: string): string => {
return x.toLowerCase();
}
n(x())
This will fail 50% of the time, when x
return a number
.
You can either make x
return just string
, or you can check the result type before calling n
:
let xr = x();
n(typeof xr === "string" ? xr: xr.toString())
Upvotes: 2