Skip to content

属性 'X' 做不 exist on 类型 'Y'

错误信息

                属性做 不 exist on 类型
              

快速摘要

你 tried 到 access 属性那个 TypeScript doesn't know 关于 on given 类型. 属性是 不 declared in 接口 or 类型.

为什么发生

  • Typo in 属性 name

  • 属性 exists at 运行时但 isn't declared in 类型

  • Accessing 属性从 错误分支的 union 类型

  • 接口是 missing 属性那个对象 actually 有

最小示例

✗ 错误代码
interface User { name: string; }
const user: User = { name: "Alice" };
console.log(user.nmae); // typo
✓ 修复代码
interface User { name: string; }
const user: User = { name: "Alice" };
console.log(user.name);

Fix typo: 'nmae' 应该是 'name'.

如何诊断

  • 检查 spelling 的属性 name

  • 验证属性是 declared in 接口/类型

  • 如果 using union 类型, narrow 它之前 accessing 类型-特定属性

  • 检查如果属性是 可选 and 可能是 undefined

如何修复

  • Fix typo in 属性 name

  • 添加 missing 属性到 接口/类型定义

  • Use 类型 assertion 如果你 know 属性 exists at 运行时

  • Narrow union 类型使用类型 guard 之前 accessing 属性

如何预防

  • Keep 接口 in sync 使用实际对象 shapes

  • Use strict 模式到 catch missing 属性

  • Consider using 记录<字符串, unknown> for 动态对象

相关资源

相关术语

← 返回语言