Skip to content

strictFunctionTypes:函数签名不兼容

快速摘要

你将函数赋值给期望不同参数变型的类型 —— strictFunctionTypes 捕获不匹配。

为什么发生

  • 期望子类型的函数被赋值给期望超类型的类型,违反参数逆变

  • 带特定参数类型的回调被传给期望更通用回调类型的函数

  • 接口方法被更窄参数类型覆盖,与基接口不兼容

最小示例

✗ 错误代码
type Handler = (event: { type: string; data: unknown }) => void;
const handler: Handler = (event: { type: 'click'; data: MouseEvent }) => { // error
  console.log(event.type);
};
✓ 修复代码
type Handler = (event: { type: string; data: unknown }) => void;
const handler: Handler = (event) => { // accept the wider type
  console.log(event.type);
};

处理器必须接受 Handler 签名期望的更宽类型(type: string),而非更窄的子类型(type: 'click')。

如何诊断

  • 阅读关于类型可赋性的 TS 错误并比较两个函数签名

  • 检查参数类型是否处于违反变型规则的子类型/超类型关系中

  • 临时禁用 strictFunctionTypes 查看错误是否消失以确认是变型问题

如何修复

  • 放宽赋值函数中的参数类型以匹配或超过目标函数类型

  • 如果确定运行时行为安全则使用类型断言

  • 重新设计接口以使用满足变型规则的一致参数类型层次

如何预防

  • 理解函数参数逆变 —— 子类型中参数应该更宽而非更窄

  • 启用 strictFunctionTypes 并从一开始就设计正确变型的接口

相关资源

相关术语

相关课程

← 返回语言