首页 > 解决方案 > 使用可选链接运算符时,类型上不存在属性“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);

标签: typescripttypescript-typingstypescript-generics

解决方案


为什么会这样?

您通过为冒险者提供一种类型来告诉 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);

推荐阅读