为什么具有必需参数的函数可以分配给参数可选的函数类型
问题
简单地说,我想知道为什么以下内容是有效的:
type Func = (param?: string) => void;
const func: Func = (param: string) => {
return;
};
问题
在实践中,这成为回调的一个问题,其中回调函数可能会使用一个或没有参数来调用,但提供的回调可能只是假设提供了一个参数,从而导致无法读取未定义的属性
错误。
是否有另一种类型安全的方法来处理可能会或可能不会使用参数调用的回调?
解决方案
需要 strictNullChecks
和 strictFunctionTypes
来使代码示例无效。感谢您将我推向正确的方向Vlaz!
Question
Simply put, I wonder why the following is valid:
type Func = (param?: string) => void;
const func: Func = (param: string) => {
return;
};
The problem
In practice, this becomes a problem for callbacks, where the callback function may be invoked with one or no parameter, but the provided callback may just assume a parameter is provided, causing cannot read property of undefined
errors.
Is there another type safe way to approach callbacks which may or may not be called with parameters?
Solution
strictNullChecks
and strictFunctionTypes
are required to invalidate the code example. Thanks for nudging me in the right direction Vlaz!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论