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

Error: "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 中的函数名称上时,我可以看到它正在 returning 一个数字:const roundToTwo: (num: number) => number.

但是当我尝试这样定义 return 类型时:

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

我收到这个错误:

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

为什么会这样或者我哪里做错了?

试试这个造型

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

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

正确的方法:

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

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

既然你是,我提供一个详细的解释。

roundToTwo是函数类型,不是数字

鉴于此定义:

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

这是 roundToTwo 的实际(正确推断)类型:

(num: number) => number

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

但是 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"

如果您只想显式键入函数表达式的return值

: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 {
   
}