问题描述
为什么此代码中没有任何编译错误?代码:
Why there aren't any compilation errors in this code?Code:
function partial(f: (a: string) => string, a: string) : string {
return "";
}
var test = () => "";
var result = partial(test, "");
函数"partial"将一个函数作为第一个参数,该函数接受一个参数,但是我将不带任何参数的函数传递给它,打字稿编译器认为这可以.我知道这不能破坏任何东西,因为您可以将世界上的所有参数传递给不需要任何东西的函数,也不会破坏任何东西,但是它应该是编译错误,因为打字稿是关于类型的,是明显的类型不匹配,很可能是开发人员的错误.
Function "partial" takes as the first argument a function, that takes one parameter, but I pass to it function, that doesn't take any parameters, and typescript compiler thinks, that this is OK. I understand that this can't break anything because you can pass all parameters in the world to the function that doesn't take any, and it won't break anything, but it should be a compilation error because typescript is about types and there is an obvious type missmatch and it can possible be a developer's error.
有没有解决此问题的方法?
Is there any workarounds for this problem?
推荐答案
这段代码显然没有错.考虑这样的事情:
There's nothing obviously wrong with this code. Consider something like this:
let items = [1, 2, 3];
// Print each item in the array
items.forEach(item => console.log(item));
此代码正确吗?确实!但是 forEach
会使用三个参数(而不是一个)调用其提供的函数.必须写:
Is this code correct? Definitely! But forEach
invokes its provided function with three arguments, not one. It would be tedious to have to write:
items.forEach((item, unused1, unused2) => console.log(item));
请注意,如果您尝试做实际上是错误的事情,仍然会出错.例如:
Note that you can still get errors if you try to do something that's actually wrong. For example:
function printNumber(x: number) { console.log(x); }
let strings = ['hello', 'world'];
strings.forEach(printNumber); // Error, can't convert string to number
这篇关于打字稿:为什么不带参数的函数可以转换为带参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!