Skip to content

类型 错误

快速摘要

你 tried 到 use 值 in 方式 那个 doesn't match 它的 类型 — 如 calling `len()` on 数字 or 添加 字符串 到 integer.

为什么发生

  • Mixing incompatible 类型 in 操作 (e.g., int + str)

  • Calling 函数 使用 实参 的 错误 类型

  • Accessing 属性 or 方法 那个 doesn't exist on 值's 类型

最小示例

✗ 错误代码
age = 25
message = "I am " + age + " years old"
✓ 修复代码
age = 25
message = "I am " + str(age) + " years old"

Python cannot concatenate 字符串 and integer — convert age 到 字符串 首先 使用 str().

如何诊断

  • 读取 错误 消息 — 它 names 类型 and 操作 involved

  • 检查 类型 的 operands 使用 typeof (JS) or 类型() (Python)

  • Trace 哪里 每个 值 came 从 到 查找 类型 mismatch

如何修复

  • Convert 值 到 正确 类型 explicitly (e.g., str(age))

  • Fix 变量 那个 持有 错误 类型 at 它的 源

  • Use 类型 guards or isinstance() 检查 之前 操作

如何预防

  • Use 类型 annotations or TypeScript 到 catch 类型 错误 at 编译 时间

  • 验证 函数 输入 之前 using 它们

相关资源

相关术语

相关课程

相关练习

← 返回语言