Reputation: 5224
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...
Upvotes: 1
Views: 294
Reputation: 23515
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;
Upvotes: 1