为什么具有必需参数的函数可以分配给参数可选的函数类型

发布于 2025-01-16 02:13:23 字数 497 浏览 2 评论 0原文

问题

简单地说,我想知道为什么以下内容是有效的:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文