Error occurred while attempting to cast the query selector result to an HTMLElement within the <script lang="ts"> section of a vue component

My Vuejs project includes a component with the following mounted method:

mounted() {
  try {
    let x = 'abc';
    console.log(x);
    let body = <HTMLElement> document.querySelector("body");
  } catch (e) {
    console.log(e);
  }
}

The compilation process using vue-cli-service lint is failing with this error:

Parsing error: Unexpected token, expected "}"
console.log(e);
......................^

My eslintrc.js configuration looks like this (using babel-eslint as the parser):

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    'plugin:vue/essential',
  ],
  rules: {
    quotes: ['error', 'single']
  },
  parserOptions: {
    parser: 'babel-eslint',
  }
};

These are the dependencies listed in package.json:

"dependencies": {
    // List of dependencies
},
"devDependencies": {
    // List of dev dependencies
}

What could be causing this issue? When I run eslint file_path, I get the same error message.

Answer №1

As per the Typescript Documentation,

...when TypeScript is used with JSX, only as-style assertions are permitted.

(This means that angle-bracket-style assertions are not allowed).

Although JSX usage in Vue is uncommon, Vue supports JSX compatibility. Hence, it is crucial to restrict type assertions to as-style. This implies replacing

let body = <HTMLElement> document.querySelector("body");

with either

const body = document.querySelector("body") as HTMLElement;

Or

const body: HTMLElement = document.querySelector("body");

Note: Substituting let with const may not have a direct impact on the question at hand. However, if reassigned to body is not needed, using const is preferred.

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

Having trouble locating the type definition file for 'cucumber' when using the Protractor framework with Cucumber and Typescript

Currently immersed in working on Protractor with Cucumber and TypeScript, encountering a persistent issue. How can the following error be resolved: Cannot locate the type definition file for 'cucumber'. The file exists within the pr ...

A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service: // UserService.ts export const create = async body => { ... save data to database ... } export const getById = async id => { ... retrieve user from database ... } The ...

Ensuring the accuracy of vue-select with vee-validate

Just getting started with VueJS. Currently exploring how to implement validation for vue-select using vee-validate. Initially attempted manual validation, but realized it's not the best approach. Experimented with vuelidate without success. Now fo ...

Remove the package from the @types folder within the node_modules directory

I currently have the 'mime' library in my node_modules directory and I am looking to completely remove it from my project, along with its @types files. The reason for this is that the old mime package is not functioning correctly for me, so I wan ...

Update the Laravel public directory

I need to update the public folder to public_html, but encountering issues with commands and functions still referencing the old public directory. While using Laravel+Vue for a single page application, my usual practice of renaming the public folder to pu ...

CPU usage spikes after launching a Cordova project in Visual Studio 2015 RTM

If you're looking for the source code of the project, you can find it at https://github.com/Yaojian/Ionic-TypeScript-Starter/. I decided to create a Visual Studio project by forking https://github.com/Justin-Credible/Ionic-TypeScript-Starter/ and fol ...

Preventing the default behavior using event.preventDefault() does not seem to be effective when submitting a

Why is the event.preventDefault() method not functioning properly? <script type="text/javascript" src="vue.js"></script> <div id="app"> <form v-on:submit.prevent="saveData"> <input type="text" name="test"> <button ...

When I declare a second service in the constructor, my modal service no longer opens as expected

Recently, I came across this login method in Angular: email: string = ""; password: string = ""; login() { const credentials = { email: this.email, password: this.password }; this.userService.login(credential ...

Utilizing form data to dynamically create HTML content

Seeking a solution to extract data from a form similar to this one: <form id="rendered-form" name="rendered-form"> <div class="rendered-form"> <div class="fb-text form-group field-text-1534368808722"> <label class="fb-text ...

Integrating modules in Angular 2

Exploring the functionalities of Angularjs 2.0, I encountered an issue when attempting to inject a service into a class. Below is the code snippet that's causing trouble: import {Component, View, bootstrap, NgFor, HttpService, Promise} from 'ang ...

Unable to create Azure CDN Endpoint: HostName entered is invalid - Ensure it is a valid domain name, IP version 4, or IP version 6

As I work on setting up an Azure CDN endpoint using CDKTF, I've hit a roadblock with an error that I'm unable to troubleshoot. The error message I'm seeing states: Error: creating Endpoint: (Name "test" / Profile Name "test-profile" / Resour ...

What could be causing a compile error in my React and TypeScript application?

I recently downloaded an app (which works in the sandbox) from this link: https://codesandbox.io/s/wbkd-react-flow-forked-78hxw4 However, when I try to run it locally using: npm install followed by: npm start I encounter the following error message: T ...

Sharing properties between components

While this topic has been discussed extensively, I am still struggling with my specific example. In my setup, I have a react-select component nested within another component, which is then part of the larger App component. SubjectSelect.tsx export default ...

Using Azure AD for authentication: Implementing Msal authentication in a React Next.js application with TypeScript and App Router

Working on a React Next.js web application with Microsoft Authentication Library (MSAL) login integration, using Azure. The app utilizes Next.js with the App Router for routing. But encountering an error when attempting to run the app: createContext only w ...

"Creating a Typescript property that is calculated based on other existing properties

I am working on a Typescript project where I have a basic class that includes an `id` and `name` property. I would like to add a third property called `displayText` which combines the values of these two properties. In C#, I know how to achieve this using ...

Execute a grandchild function in Angular that triggers its grandparent function

I'm currently working with a component structure that looks like this: Component A -> Component B -> Component C Within the template of Component C, there is a button that triggers a function in the 'code behind' when clicked. My go ...

Sending Component Properties to Objects in Vue using TypeScript

Trying to assign props value as an index in a Vue component object, here is my code snippet: export default defineComponent({ props:{ pollId:{type: String} }, data(){ return{ poll: polls[this.pollId] } } }) Encountering errors wh ...

Guide to incorporating a vanillaJS npm script into a Nuxt plugin

Struggling with saving images directly to AWS S3 using AWS S3. Attempted to add the AWS package as a plugin without success. In the nuxt.config.js file, I have: plugins: [ ... '~plugins/S3.js' ], In the plugins/s3.js file: import vue from ...

Extract TypeScript classes and interfaces from a consolidated file

I am seeking a way to consolidate the export of my classes, interfaces, and enums from multiple files into a single file. In JavaScript, I achieved this using the following method: module.exports = { Something = require("./src/something").default, ...

What is the correct way to send a GET request in angular?

Trying to make a GET request from Angular to Spring Java, but encountering error code 415 zone.js:3243 GET http://localhost:8080/user/friend/1 415 Below is my Spring Java code for the endpoint: @RequestMapping( value = "/friend/{idUser}", ...