为什么TypeScript不推断输入参数的类型

为什么TypeScript不推断输入参数的类型,typescript,Typescript,我有一个TypeScript中的代码示例: function twice(x:number) { return x*2; } function calltwice(y) { return twice(y); } 它在node中编译和执行 我想知道为什么y的类型是任何?我希望它被推断为数字,因为它被传递给只接受数字的tweeps函数。而这种期望基本上是由F#引起的: 谁知道calltweeps是int->int您可以指定参数和返回类型: function twice(x: numb

我有一个TypeScript中的代码示例:

function twice(x:number) {
   return x*2;
}

function calltwice(y) {
   return twice(y);
}
它在node中编译和执行

我想知道为什么y的类型是任何?我希望它被推断为数字,因为它被传递给只接受数字的tweeps函数。而这种期望基本上是由F#引起的:


谁知道calltweeps是int->int

您可以指定参数和返回类型:

function twice(x: number): number {
   return x*2;
}

function calltwice(y: number): number {
   return twice(y);
}
在这种情况下,编译器将在编译期间检查类型


注意:Typescript编译成JavaScript,在执行过程中根本不会检查类型。因此(如果您将从JavaScript调用此代码),您可以将任何对象传递给这些函数。

您的调用堆栈从
calltweep
开始,并且
y
参数被推断为any。在这个
tweeds(y)
调用不会抛出任何错误,因为
y
属于any类型。我想你是想换个角度看问题。您只需为y@
函数calltweep(y:number)指定类型即可。
calltweep返回类型也可以使用表达式
ReturnType
function twice(x: number): number {
   return x*2;
}

function calltwice(y: number): number {
   return twice(y);
}