微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用函数类型限制Typescript中的函数定义

如何解决使用函数类型限制Typescript中的函数定义

根据文档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,30); // I had to give three parameters
console.log(result);

这也可以。它没有显示任何错误。我期望它会出现错误,因为函数定义中未使用num3。

这也令人困惑,因为我不能用两个参数调用 myfunc

不可能根据接口来严格定义函数定义吗?

解决方法

这是因为TypeScript实际上允许丢弃参数。 From their documentation

您可能想知道为什么我们允许“丢弃”参数[...]。之所以允许这种分配,是因为在JavaScript中实际上忽略了多余的函数参数。

在您的示例中,function (num1: number,num2: number)function (one: number,two: number,three: number)的子类型,因此被视为有效。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。