错误:"Type '(num: number) => number' is not assignable to type 'number'.(2322)"



当我有这样的函数时,我没有得到任何抱怨:

const roundToTwo = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2");
};

当我将鼠标悬停在VS Code中的函数名称上时,我可以看到它返回了一个数字:const roundToTwo: (num: number) => number

但是当我试图定义这样的返回类型时:

const roundToTwo: number = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2");
};

我得到这个错误:

Type '(num: number) => number' is not assignable to type 'number'.

为什么这或者我做错了什么?

由于您对语法和语义都感到困惑,我将提供详细的解释。

roundToTwo是函数类型,而不是数字

给定此定义:

const roundToTwo = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}

这是roundToTwo:的实际类型

(num: number) => number

为什么?因为roundToTwo是一个函数类型,而不是一个数字。类型是从分配给它的函数表达式推断出来的。记住,在Javascript中,函数是第一类对象。同样,在Typescript中,它们也是第一类类型。

const roundToTwo: number赋予它类型number

这就是你在新定义开始时错误地做的事情。你说;roundToTwo是一个数字";然后你试图给它分配一个函数,得到一个预期的类型错误:

const roundToTwo: number = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}
// compare the above to:
const roundToTwo: number = 2
const n: number = 2

没有必要显式键入

完全没有必要显式键入roundToTwo,因为您立即为它分配了一个函数表达式,而且推断的类型是您想要的。就像您不需要将: number添加到此声明中一样:

const max = 42  // same as "const max: number = 42"

如果您只是想显式键入函数表达式的返回值

:number放在参数签名之后,如下所示:

const roundToTwo = (num: number):number => {
return +(Math.round(+(num + "e+2")) + "e-2")
}

如果要显式键入roundToTwo变量

你有两个选择。

内联语法:

const roundToTwo: (num: number) => number = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}

使用类型别名

type numericFunction = (num: number) => number
const roundToTwo: numericFunction = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}

类型别名更可读,尤其是对于更复杂的函数签名,但更重要的是,如果您必须在其他地方引用此函数类型,例如作为函数参数:,则它非常有用

function scaleArray(arr: number[], scaleFunc: numericFunction): number {

}

显示的错误不言自明。roundToTwo的返回类型是(num: number) => number,而不仅仅是number。当您已经通过函数间接指定了返回类型(不过Typescript会这样做(时,直接指定基元是不对的。

正确的方式:

const roundToTwo: (num: number) => number = function (num: number) {
return +(Math.round(+(num + "e+2")) + "e-2");
};

或者不直接指定类型而直接将其保留。Typescript无论如何都会应用该类型,因为初始化发生在声明时。

试试这个形状的

type roundToTwo=(num:number)=>number

const roundToTwo :roundToTwo= (num:number)=> {
return +(Math.round(+(num + "e+2")) + "e-2");
};

相关内容

最新更新