'Optional types cannot be assigned to one of them (TypeScript)

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!



Solution 1:[1]

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())

Playground Link

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())

Playground Link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Titian Cernicova-Dragomir