Typescript为什么不允许扩展此参数类型的给定函数参数?
这一定很简单,但我不明白为什么typescript会抛出错误 稍微调整一下:Typescript为什么不允许扩展此参数类型的给定函数参数?,typescript,Typescript,这一定很简单,但我不明白为什么typescript会抛出错误 稍微调整一下: type Fruit = "Orange" | "Apple" | "Banana"; const myFruit: Fruit = "Apple"; const myString: string = myFruit; //accepted! // now with functions type fruitFunc = (key: F
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)
为什么会这样?我不是想给水果分配一个字符串,但恰恰相反……类型脚本告诉您,
string
与“Orange”|“Apple”|“Banana”
不兼容,这是正确的
我知道你告诉自己,“橙色”|“苹果”|“香蕉”
都是字符串,所以typescript应该允许函数赋值,但它不是typescript的工作方式
这里输入是为了确保函数得到它们所要求的。例如,函数myFruitFunc
正在等待Fruit
作为参数,如果您向其发送Plant
,函数将不会准备好,并且将出现意外行为
将等待结果的myFruitFunc
放入将等待字符串的函数指针中,会导致函数的使用不安全
这就是为什么typescript会给您带来一个错误
综合考虑,如果您仍然想将myFruitFunc
存储到myStringFunc
中,您可以强制转换函数,告诉typescript
没关系,我知道我在做什么
谢谢你的回答-但是在我的代码中,defenitionstringFunc
类型非常大而且难看,并且存在于其他文件中(我在React中编写,所以它是该组件的一个道具)。没有其他方法可以对Typescript说‘嘿,我知道我在做什么,允许参数扩展参数的类型’,而不处理整个类型定义?
const myStringFunc: stringFunc = myFruitFunc as stringFunc;