简体   繁体   English

打字稿 - 具有通用道具类型的回调

[英]Typescript - callback with generic prop type

I have code like below, myFunc requires callback which needed generic parameter.我有如下代码, myFunc需要需要generic参数的callback

It looks like I can pass function which not required any parameters and not getting any error notification, any idea why?看起来我可以传递不需要任何参数并且没有收到任何错误通知的函数,知道为什么吗?

const myFunc = <T>(callback: (par: T) => void) => {
  const param = ('test' as any) as T;
  callback(param);
};

const callback = (par: number) => {
  console.log(par);
};

myFunc<string>(callback); // Not working as suspected - OK
myFunc<string>(() => {}); // Why I do not getting any error notification here?

This is clearly described in handbook.这在手册中有清楚的描述。 Comparing two functions : 比较两个函数

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

You may be wondering why we allow 'discarding' parameters like in the example y = x.您可能想知道为什么我们允许像示例 y = x 中那样“丢弃”参数。 The reason for this assignment to be allowed is that ignoring extra function parameters is actually quite common in JavaScript.允许这种赋值的原因是忽略额外的函数参数在 JavaScript 中实际上很常见。 For example, Array#forEach provides three parameters to the callback function: the array element, its index, and the containing array.例如,Array#forEach 为回调函数提供了三个参数:数组元素、其索引和包含的数组。 Nevertheless, it's very useful to provide a callback that only uses the first parameter尽管如此,提供一个只使用第一个参数的回调是非常有用的

See also relevant section of TypeScript FAQ: Why are functions with fewer parameters assignable to functions that take more parameters?另请参阅 TypeScript 常见问题解答的相关部分: 为什么参数较少的函数可以分配给参数较多的函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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