类型 '字符串' 是不 assignable 到类型 '数字'
错误信息
类型 '字符串' 是不 assignable 到类型 '数字'
快速摘要
你 tried 到 assign 值的 one 类型到 变量 or 参数的 不同, incompatible 类型. TypeScript caught mismatch at 编译时间.
为什么发生
Assigning 字符串到 数字-输入变量 (or vice versa)
Returning 错误类型从 函数
Passing 错误类型 as 函数实参
类型 annotation 那个 doesn't match 实际值
最小示例
✗ 错误代码
let count: number = 10;
count = "twenty";✓ 修复代码
let count: number = 10;
count = 20;数量是 输入 as 数字, 所以 assign 数字值, 不字符串.
如何诊断
检查类型 annotation on 变量/参数针对值 是 assigned
Use
typeof到检查运行时类型如果 unsureLook at 错误消息 — 它 tells 你两者都源 类型 and 目标类型
如何修复
更改类型 annotation 到 match 值 (e.g.,
: 字符串相反的: 数字)更改值 到 match 类型 (e.g., 移除 quotes 从数字)
Convert 值到 正确类型 (e.g.,
数字(str)or字符串(编号))
如何预防
启用 strict 模式到 catch 类型 mismatches early
Use 类型 inference 哪里可能到 avoid annotation mistakes
编写单元测试那个验证类型 correctness