Skip to content

实参的 类型 'X' 是不 assignable 到参数的 类型 'Y'

错误信息

                实参的 类型是 不 assignable 到参数的 类型
              

快速摘要

你通过值 到函数, 但值's 类型 doesn't match 函数's 参数类型.

为什么发生

  • Passing 字符串哪里数字是 expected (or vice versa)

  • Passing 对象那个's missing 必需属性

  • Passing 值从 union 类型不使用 narrowing 首先

  • 函数参数类型是 也 narrow for 实参

最小示例

✗ 错误代码
function double(x: number): number { return x * 2; }
double("5"); // string, not number
✓ 修复代码
function double(x: number): number { return x * 2; }
double(Number("5")); // convert to number

Convert 字符串到 数字之前 passing 它到 函数.

如何诊断

  • 检查函数's 参数类型针对实参's 类型

  • Look at 两者都类型 in 错误消息

  • 检查如果实参 comes 从 union 那个需要 narrowing

如何修复

  • Convert 实参到 expected 类型

  • Widen 函数's 参数类型到 接受实参

  • Narrow 实参's 类型之前 passing 它

  • 添加类型 assertion 如果你 know 类型是 compatible

如何预防

  • Use IDE tooltips 到检查参数类型之前 calling

  • 启用 strict 模式 for thorough 类型检查

相关资源

← 返回语言