1

it must be an easy one but I can't figure out why typescript throws an error.

taking this question and tweaking at a little bit:

type Fruit = "Orange" | "Apple" | "Banana";
const myFruit: Fruit = "Apple";
const myString: string = myFruit;   //accepted!

// now with functions
type fruitFunc = (key: Fruit) => void;
type stringFunc = (key: string) => void;
const myFruitFunc: fruitFunc = (key: Fruit) => {};
const myStringFunc: stringFunc = myFruitFunc;   //Error!
// Type 'fruitFunc' is not assignable to type 'stringFunc'.
//   Types of parameters 'key' and 'key' are incompatible.
//     Type 'string' is not assignable to type 'Fruit'.ts(2322)

Why is that happening? I'm not trying to assign a string to fruit, but the opposite...

Eliav Louski
  • 3,593
  • 2
  • 28
  • 52

1 Answers1

1

Typescript tells you that string is not compatible with "Orange" | "Apple" | "Banana" which is true.

I know you tell yourself that "Orange" | "Apple" | "Banana" are all strings, so typescript should allow the function assignation but it's not how typescript works.

Typing is here to ensure that functions gets what they asked for. For example, the function myFruitFunc is waiting for Fruit as parameter, if you send a Plant to it, the function won't be prepared and will have unexpected behavior.

Putting the myFruitFunc that is waiting for Fruit inside a function pointer that would wait for a string, makes the use of the function unsafe.

That's why typescript is raising you an error.


All considered, if you still wants to store myFruitFunc into myStringFunc you can cast your function, telling typescript

it's okay, I know what I'm doing.

const myStringFunc: stringFunc = myFruitFunc as stringFunc;
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • thank you for the answer - but in my code the type defenition `stringFunc` is pretty big and ugly and exist in other file(I'm writing in React - so it's a prop of that component). there is no other way saying to Typescript 'hey, I'm know what I'm doing,allow parameters that extends the type of the parameters' without coping the entire type definition? – Eliav Louski Jul 23 '20 at 09:57