如何在Typescript函数类型中强制使用强制性参数?

苏迪普

我是Typescript的新手,对函数类型有疑问。

我有以下类型:

type IMyTest<R> = (
    arg1: number,
    arg2: string,
    arg3: number
) => R;

现在,以下签名是有效的(不会给我一个错误),而且我不明白其有效性的原因。根据我的理解,arg2并且arg3不会使用“?”标记为可选。符号,因此TypeScript编译器应引发错误,但不是:

const myTest3: IMyTest<string> = (arg1: number):string => {

    return "any string";
};

在操场上的现场例子

有什么方法可以使参数成为强制性的吗?

现在,arg1?:string与arg1:string相同。根据我的理解,没有“?” 符号,必须有一个参数。但是,这里不是这种情况。

Aleksey L.

看一下类型兼容性规则

let x = (a: number) => 0;
let y = (b: number, s: string) => 0;

y = x; // OK
x = y; // Error

允许使用“丢弃”参数(如您的示例中所示),因为实现过程并不关心是否提供了这些参数(在运行时不会出现任何错误)。

实际上,这种模式在JavaScript中很常见。例如,Array#forEach为回调函数提供了三个参数:数组元素,其索引和包含数组。不过,提供仅使用第一个参数的回调非常有用。

const items = [1, 2, 3];

// Don't force these extra parameters
items.forEach((item, index, array) => console.log(item));

// Should be OK!
items.forEach(item => console.log(item));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章