VSCode IntelliSense 在 TypeScript 中的可选链接上显示错误

问题描述 投票:0回答:1

在 VSCode 中,IntelliSense 表示 TypeScript 文件中的对象上不存在属性,即使我指定可选链接语法来短路错误也是如此。代码正确编译为 JavaScript es2020。

这是打字稿代码

"use strict"
const animals = {
    dog: {
        name: 'Rover'
    }
};
const catName = animals.cat?.name;          ** *<<<<< the squiggly line appears under cat***
console.log(catName);

实际的 TypeScript 错误是

    error TS2339: Property 'cat' does not exist on type '{ dog: { name: string; }; }'.

我知道 VSCode 附带了自己的 Typescript 版本,因此我将以下内容添加到我的工作区设置中。

{
    "typescript.tsdk": "node_modules/typescript/lib",
}

当我将鼠标悬停在 VSCode 状态栏上的打字稿版本号上时,它会显示以下内容,这是一个有效的路径。

D:\项目 est-ts ode_modules ypescript\lib sserver.js

我还尝试禁用所有 VSCode 扩展,但这并没有改变结果。

我的VSCode版本是1.88.1 我的 TypeScript 版本是 5.45

仅供参考,我使用的是 Windows 10。

我对其他帖子的所有研究和审查都回到了打字稿的“typescript.tsdk”设置,但这并没有解决问题。

下面是我的 tsconfig.json 文件。

{
"compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "rootDir": "./src",
    "outDir": "./js",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
},
  "include": [
    "src"
  ]
}

如何消除 VSCode 中显示的错误?

javascript typescript intellisense optional-chaining
1个回答
0
投票

您的 TypeScript 安装没有任何问题,事实上它正在做它应该做的事情。让我们在这里分解一下这个问题:

const animals = {
    dog: {
        name: 'Rover'
    }
};

您有一个具有推断类型的常量定义,可以像这样显式地编写

type Animals = {
  dog: {
    name: string
  }
}

如果您希望更加灵活,那么您需要手动扩展类型或完全放松类型。

解决方案#1

假设您想要各种动物,并且它们叫什么并不重要(即

cat
dog
bird
...),您可以这样做:

type Animals = {
  [key: string]: {
    name: string
  }
}

const animals: Animals = {
    dog: {
        name: 'Rover'
    }
};

const catName = animals.cat?.name; 
console.log(catName);

这里我们有一个类型

Animals
,它可以包含任何类型的动物,它只是一个具有属性
name
的对象。

解决方案#2

如果您想明确只允许

cat
dog
的动物,那么您可以执行以下操作

type Pet = {
  name: string
}

type Animals = {
  cat?: Pet,
  dog?: Pet,
}

const animals: Animals = {
    dog: {
        name: 'Rover'
    }
};

const catName = animals.cat?.name; 
console.log(catName);

注意:在这种情况下,可以同时定义

cat
dog
,也可以同时定义
undefined
,或者定义和
undefined

的组合

解决方案#3

如果你希望这些对象的行为像普通的 JS 对象一样,基本上可以包含任何键/值,你也可以使用更宽松的类型,如

Record

const animals: Record<string, any> = {
    dog: {
        name: 'Rover'
    }
};

const catName = animals.cat?.name; 
console.log(catName);

我建议尽可能不要使用

any
,因为它在某种程度上违背了 TS 的目的,但您也可以将其替换为您想要的任何类型,例如

const animals: Record<string, { name: string }> = {
    dog: {
        name: 'Rover'
    }
};

甚至更好

const animals: Record<'cat' | 'dog', { name: string }> = {
    dog: {
        name: 'Rover'
    }
};

如何使用TypeScript记录

© www.soinside.com 2019 - 2024. All rights reserved.