Errors in Visual Studio regarding typescript are often not found by tsc and eslint, causing frustration for developers

Today, after restarting my computer and launching visual studio code, I encountered an unfamiliar error that I've never seen before:

https://i.sstatic.net/z1vw5.png

I haven't made any changes to my project's code (confirmed by running git status). It's unclear whether this issue emerged today or if it has been occurring unnoticed for some time. However, five days ago, these errors were not present, even though the problematic code has been in place longer than that. Here is the snippet causing the error:

        } catch (e) {
            if (typeof e === "string") {
                throw new Error(
                    `...: ${e}`
                );
            } else {
                e.message = `... ${e.message}`;
                throw e;
            }
        }

When running tsc or eslint, no complaints are raised about this particular error. My preference is for vscode to identify issues in line with tsc/eslint rules rather than implementing its own type checking protocols. How can I resolve these discrepancies?

I'm unsure of what I need to rectify. Perhaps attaching my settings could shed some light on the situation:

user

{
    "files.autoSave": "afterDelay",
    "explorer.confirmDelete": false,
    "security.workspace.trust.untrustedFiles": "open",
    "explorer.confirmDragAndDrop": false,
    "docker.showStartPage": false,
    "editor.fontSize": 14,
    "editor.renderWhitespace": "all",
    "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "typescript.tsserver.experimental.enableProjectDiagnostics": true
}

Although toggling

typescript.tsserver.experimental.enableProjectDiagnostics
had no impact on the error message.

workspace

{
    "workbench.editorAssociations": {
        "*.ipynb": "jupyter-notebook"
    },
    "notebook.cellToolbarLocation": {
        "default": "right",
        "jupyter-notebook": "left"
    },
    "python.formatting.provider": "black",
    "eslint.workingDirectories": [
    "./firebase/functions",
    ],
    "eslint.format.enable": false,
    "prettier.enable": true,
    "[typescript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[jsonc]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    "typescript.format.semicolons": "insert",
    "editor.detectIndentation": false,
    "prettier.configPath": "firebase/functions/.prettierrc.json"
}

Below is a redacted version of my package.json file:

{
  "name": "...",
  "scripts": {
    "lint": "eslint .",
    "build": "tsc --build .",
    "test": "npm run lint && npm run build && ...",
    ...
  },
  "engines": {
    "node": "12"
  },
  "main": "lib/index.js",
  "dependencies": {
    "@firebase/testing": "^0.20.8",
    "@types/child-process-promise": "^2.2.1",
    "@types/follow-redirects": "^1.13.0",
    "@types/node-fetch": "^2.5.7",
    "@types/progress": "^2.0.5",
    "@types/request": "^2.48.7",
    "@types/uuid": "^8.3.0",
    ...
  },
  "devDependencies": {
    "@types/mocha": "^9.0.0",
    "@types/node": "^14.10.2",
    "@typescript-eslint/eslint-plugin": "^4.28.5",
    "@typescript-eslint/parser": "^4.28.5",
    "eslint": "^7.31.0",
    "firebase-functions-test": "^0.2.2",
    "lodash": "^4.17.21",
    "mocha": "^8.1.3",
    "prettier": "^2.3.2",
    "typescript": "^3.9.7"
    ...
  },
  "private": true
}

(The package.json file contains unrelated complexities, which I apologize for; they are part of the legacy system that I am actively working on enhancing).

Here is my tsconfig.json:

{
    "compilerOptions": {
        "rootDir": ".",
    },
    "files": [],
    "references": [
        {
            "path": "./src"
        },
        {
            "path": "./test"
        },
    ]
}

Note that this file resides in ./firebase/functions, not at the project root level.

Provided below is the

./firebase/functions/src/tsconfig.json
:

{
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "../lib",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "sourceMap": true,
    "strict": true,
    "lib": ["es2020", "dom"],
    "target": "es2019",
    "composite": true,
    "allowSyntheticDefaultImports": true
  },
  "compileOnSave": true,
  "types": ["node", ...],
  "include": ["**/*.ts"]
}

Lastly, the contents of

./firebase/functions/test/tsconfig.json
are as follows:

{
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "../libtest",
    "strict": false,
    "composite": true,
    "sourceMap": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  },
  "include": [
    "**/*.ts"
  ]
}

What steps should I take to align visual studio code's error reporting with that of my tsc and eslint setups - maintaining consistency without unnecessary deviations?

Answer №1

It seems like your Visual Studio Code is running a newer version of TypeScript compared to what is specified in your package.json file. This could be causing errors in catch blocks as they are now being treated as unknown instead of any. To resolve this issue, simply look at the bottom right corner of your VS Code window where you should see the TypeScript version displayed, similar to:

https://i.sstatic.net/OWwFC.png

Click on the version number and a dropdown menu will appear at the top of the screen.

https://i.sstatic.net/MjKZV.png

Choose "Select TypeScript Version" from the dropdown to make changes.

In most cases, VS Code can automatically detect your workspace's version of TypeScript and list it as an option. However, if it fails to do so or if you prefer using a different version, you can specify the TypeScript version by setting the "typescript.tsdk" property. For detailed instructions on how to configure this, refer to this page: https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-the-workspace-version-of-typescript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to reduce the size of TypeScript source code in an Electron application with the help of Electron Forge and Electron Packager

resolved: I was able to solve this issue using electron-builder, which utilizes webpack in the background to handle all problems efficiently. Initially, I faced this challenge while using electron-forge and electron-packager. Despite researching extensivel ...

Using Jasmine to Jest: Mocking Nested function calls

I am currently working on testing my TypeScript functions with Jasmine: //AB.ts export async function A() { } export async function B() { A(); } My goal is to unit test function B by mocking out function A to see if it is called. Here is the code I h ...

Obtain the specific generic type that is employed to broaden the scope of a

I am working on a class that involves generics: abstract class Base<P extends SomeType = SomeType> { // ... } In addition, there is a subclass that inherits from it: class A extends Base<SomeTypeA> { // ... } I'm trying to figure out ...

The issue with IONIC/Angular lies in its inability to properly render the JSON data retrieved

I have recently started learning IONIC/Angular and Javascript, although I do have some background in other programming languages. The issue I'm currently facing is related to fetching JSON data from an external API (I've created the API with Stra ...

typescript tips for incorporating nested types in inheritance

I currently have a specific data structure. type Deposit { num1: number; num2: number; } type Nice { num: number; deposit: Deposit; } As of now, I am using the Nice type, but I wish to enhance it by adding more fields to its deposit. Ultima ...

What is the proper method for implementing an event listener exclusively for a left mouse click?

Is there a way to make Phaser recognize only left mouse clicks as click events, excluding right and middle clicks? Check out this Phaser example at the following link: https://phaser.io/examples/v2/basics/02-click-on-an-image. ...

Limiting the defaultValue of a select to one of the values of its options in TypeScript: A guide

Is there a way to configure the Select component's properties so that the defaultValue is limited to one of the predefined options values ("au" | "nz" in this scenario)? const countryOptions = [ { value: "au", l ...

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

Angular: Verify that all services are fully executed before proceeding to the next step

We have adopted Angular for our project. Our component receives data from an API, which is then processed by Data Services. These services transform the data by combining first and last names, rounding dollar amounts, performing calculations, etc. The fina ...

Angular Protectors: Stop unauthorized access to a URL while allowing authorized refresh

I've developed a Protection feature that blocks users from directly accessing a specific URL, and it's functioning correctly. However, the issue arises when I try to refresh the page as the Protection feature ends up redirecting me. Below is th ...

Resolving the Angular NG0100 Error: Troubleshooting the ExpressionChangedAfterItHasBeenCheckedError

I am currently working on implementing a dialog component that takes in data through its constructor and then utilizes a role-based system to determine which parts of the component should be displayed. The component code snippet looks like this: export cl ...

What is the best way to implement a dynamic back button in Next.js?

Being familiar with creating a standard back button, I am now eager to craft one that directs the user back by one step in the URL rather than returning to the previous page. This way, I can utilize the button in various locations without needing to alter ...

Is it feasible to restrict a generic type using typeguard?

I'm currently working on refining a generic function, where the autocomplete feature recognizes that it's encountering a typeguard, preventing it from revisiting the same code block. I suspect that the issue lies in not restricting the type to th ...

How do I maintain the Type<any> throughout my application state in NgRx without compromising on best practices?

Utilizing Angular 11.1.2 and rxjs 6.6.2 I am working on developing an application that dynamically displays a list of components. I have successfully achieved this functionality independently. However, I am currently encountering challenges when transitio ...

Is it possible to confirm the authenticity of a hashed secret without having knowledge of the salt used

My method of storing API-Keys involves hashing and saving them in a database. ... async function createToken(userId:number) { ... const salt=await bcrypt.genSalt(15) const hash=await bcrypt.hash(token, salt) await db.store({userId,hash}) } ...

Steps for resolving the error message: "An appropriate loader is required to handle this file type, but there are no loaders currently configured to process it."

I am encountering an issue when working with next.js and trying to export a type in a file called index.ts within a third-party package. Module parse failed: Unexpected token (23:7) You may need an appropriate loader to handle this file type, current ...

Navigating through Angular to access a component and establishing a data binding

I am looking for the best way to transition from one component to another while passing data along with it. Below is an example of how I currently achieve this: this.router.navigate(['some-component', { name: 'Some Name' }]); In Some ...

The correlation between a TypeScript class and an interface bearing an identical name

I have been struggling to find clear documentation or explanation for the unique relationship between a TypeScript class and an interface that share the same name. What is the significance of having an interface with the same name as a class? Why does a ...

Error message encountered in Typescript eslint: File extension "ts" is missing in import statement for the specified file

I am encountering an issue with my Node/Express application created using Typescript. The problem lies in eslint throwing an error that says: Missing file extension "ts" for "./lib/env" import/extensions Below is the content of my .eslintrc file: { ...

Unable to retrieve values from nested objects in component.html

Hey fellow tech enthusiasts, I'm currently dealing with a complex nested JSON object retrieved from an API. Here's a snippet of the object: profile : { title:"Mr", personalInfo:{ fullNames: "John Doe", id ...