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:

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:

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

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 causes the canLoad function to create an endless loop when rerouting?

Utilizing Angular's canLoad function in my AuthGuard to authenticate a lazy loaded module at the root of my application. If the user is not authenticated, the module will not load and the user will be directed to the login page. This process works sm ...

Obtain the combination of values within an array object

I am attempting to write the specifications for a function that can take records of any structure and convert the values into a discriminated union. For example: const getKeys = <T extends {key: string}>(items: T[]): T['key'] => { // ...

Effectively enhance constructor by incorporating decorators

Is it possible to properly extend a class constructor with decorators while maintaining the original class name and static attributes and methods? Upon reading the handbook, there is a note that cautions about this scenario: https://www.typescriptlang.or ...

What is the use of the typeof operator for arrays of objects in TypeScript?

How can I update the any with the shape of the options's object below? interface selectComponentProps { options: { label: string; value: string; }[]; } const SelectComponent: React.FC<selectComponentProps> = ({ options, }) => ...

Oops! The formGroup function in Angular 5 requires an instance of a FormGroup

While working with Angular 5, I encountered an error in this basic form. Here is the issue: Error Message: EditVisitanteDialogComponent.html:10 ERROR Error: formGroup expects a FormGroup instance. Please pass one in. Example: > > &l ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

Obtain the value of a template variable in Angular 2

I am seeking information on how to access the values of selected items in templates. Specifically, I want to understand how to retrieve the selected value of IPMIDisplayTime and IPMIDisplayTime within the template for later use. import {ViewChild, Elem ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Is there a way to modify the id parameter in the URL using Angular 2's ActivatedRoute?

How can I modify a parameter in the URL without altering the overall address? https://i.stack.imgur.com/LOd4T.png This is the TypeScript code that I currently have: onRowClicked(event: any) { let currentIdPerson = event.data.IdPerson; } I am trying ...

Ways to invoke the function in a separate component

How can I use ViewChild to call a method in a different component? I have a method in the piechart component that I want to access from the app component using ViewChild. In my piechart.component.ts file: export class PiechartComponent { constructor() ...

What is the process of invoking an external JavaScript function in Angular 5?

I recently downloaded a theme from this source. I need to specify script and CSS in the index.html file. The body section of index.html looks like this: <body> <app-root></app-root> <script type="text/javascript" src="./assets/js ...

Setting multiple values on a form can be accomplished by using the appropriate form fields

When it comes to setting values on fields, I am aware that I can choose between using setValue or patchValue However, I am currently encountering a situation where I need to avoid setting the value on each field individually. Take a look at my f ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

Assembly of Components

As someone new to angular, I am currently in the process of building an angular2 application. My goal is to dynamically create a series of DOM components using the data provided below: // Class construct with properties sorted alphabetically export class ...

Error message: "ReferenceError occurred while trying to access the Data Service in

As I embark on the journey of creating my very first MEAN stack application - an online cookbook, I have encountered a challenge in Angular. It seems like there is an issue between the service responsible for fetching recipe data from the API (RecipeDataSe ...

The output from the second request using RxJS

I am facing an issue with returning an Observable from the second request. Here is the scenario I am encountering: commandRequest(action:string, commandData:any):Observable<CashDesckResponse> { let command:CashDeskRequest; //ask my backend f ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

How can I add a new key value pair to an existing object in Angular?

I'm looking to add a new key value pair to an existing object without declaring it inside the initial object declaration. I attempted the code below, but encountered the following error: Property 'specialty' does not exist on type saveFor ...

Encountering a TypeError while attempting to retrieve an instance of AsyncLocalStorage

In order to access the instance of AsyncLocalStorage globally across different modules in my Express application, I have implemented a Singleton class to hold the instance of ALS. However, I am wondering if there might be a more efficient way to achieve th ...