简体   繁体   中英

Why TypeScript does not infer types of input arguments

I have this code example in TypeScript:

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

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

It compiles and execution in node gives NaN.

I am wondering why type of y is any? I expected it to be inferred as number because it is passed to twice function which can take only number. And this expectation was basically caused by F#:

let twice x = x*2
let calltwice y = twice y

who exactly knows that calltwice is int->int

You can specify argument and return type:

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

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

In this case compiler will check types during compilation.

Note: Typescript compiles into JavaScript, and during execution it will not check types at all. So potentially (if you will call this code from JavaScript) you can pass any object to these functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM