根据文档https://www.typescriptlang.org/docs/handbook/interfaces.html#function-types
我想限制一个函数的参数。我已经这样写了函数。...
interface FuncType {
(one: number, two: number, three: number): number;
}
let myfunc: FuncType = function (num1: number, num2: number, num3: number) {
return num1 + num2 + num3;
}
let result = myfunc(10,20,30);
console.log(result);
这很好。但是问题是,如果我这样做...
let myfunc: FuncType = function (num1: number, num2: number) { //num3 is missing
return num1 + num2;
}
// let result = myfunc(10,20); //this gives an error.
let result = myfunc(10,20,30); // I had to give three parameters
console.log(result);
这也可以。它没有显示任何错误。我期望它会出现错误,因为函数定义中未使用num3。
这也令人困惑,因为我不能用两个参数调用 myfunc 。
不可能根据接口来严格定义函数定义吗?
答案 0 :(得分:1)
这是因为TypeScript实际上允许丢弃参数。 From their documentation:
您可能想知道为什么我们允许“丢弃”参数[...]。之所以允许这种分配,是因为在JavaScript中实际上忽略了多余的函数参数。
在您的示例中,function (num1: number, num2: number)
是function (one: number, two: number, three: number)
的子类型,因此被视为有效。