typescript - 使用可选链接运算符时,类型上不存在属性“x”
问题描述
我想在打字稿中使用可选链接运算符,但出现错误Property 'dog' does not exist on type '{ name: string; cat: Record<string, string>; }'.
。从打字稿中抱怨错误是完全有道理的,但我想知道是否让我四处走动?
操场
const adventurer: {name: string;cat:Record<string, string>} = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer?.dog;
console.log(dogName);
解决方案
为什么会这样?
您通过为冒险者提供一种类型来告诉 TS 编译器,该类型adventurer
永远不会有属性dog
(编辑:感谢@jcalz 指出这并不完全正确。请查看下面的评论以获取更多信息)。解决这个问题有两种主要方法:
通过断言另一种类型(如任何类型)告诉 TypeScript 你更了解
const dogName = (adventurer as any)?.dog;
console.log(dogName);
将冒险者的类型更改为可选地包括dog
const adventurer: {name: string;cat:Record<string, string>; dog?: string} = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer?.dog;
console.log(dogName);
推荐阅读
- python - Python pyautogui单击弹出按钮不起作用?
- javascript - 当存储在变量中时,Socket.io 发射到 socket.id 不起作用
- html - 如何通过双击从禁用状态启用选择标签?
- apache-kafka - kafka 的问题 - 结果“退出代码”失败,状态 = 1/FAILURE
- concrete5 - php7 xampp 上的 Concrete5 数据库导入问题
- datetime - DateTime 到 Java.Util.Date 的转换在 Android 的 DST 开始和结束时间错误呈现
- android - 使用数据绑定的 Textview 可见性
- javascript - 我的地图功能在反应 js 中不起作用
- filter - JAX-RS ContainerRequestFilter - 修改 QueryParam 的
- laravel - 在 Vue JS 中使用 Watchers 的警报