kiker iz
kiker iz

Reputation: 1

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!

Upvotes: 0

Views: 41

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

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

Upvotes: 2

Related Questions