Identifying an Incorrect Function Call in a TypeScript Function from a JavaScript File [TypeScript, Vue.js, JavaScript]

I have a vue2 application and I am looking to incorporate TypeScript into some service files without modifying the existing js/vue files.

To enable TypeScript support, I utilized vue-cli which allowed me to successfully add a myService.ts file containing a TypeScript function called myFunction. Within this file, Vue properly detects type issues. I am able to import this service into a vue component file - myComponent.vue (which contains js code) and use it seamlessly.

The structure of myFunction is as follows:

function myFunction(x: number, y: number): number {
  const a: number = 3;
  const b: number = 2;
  return a + b + x + y;
}

However, when invoking myFunction from myComponent.vue with incorrect parameters such as myFunction("str1", "str2"), Vue does not flag any issues, even though string parameters should be invalid. I can execute npm run serve without encountering any warning or error messages.

Is there a way to prompt Vue to detect these errors? Can TypeScript issues within js code be identified?

Answer №1

Absolutely, typing checking JavaScript files is indeed achievable with TypeScript, but the proper configuration in your tsconfig file is a prerequisite.
Explore all available options for tsconfig here

Essential requirements include:
allowJs option
checkJs option

In addition, you can insert // @ts-check at the beginning of every js file you wish to type check, rather than globally enabling this feature for the entire project.

UPDATE:
I noticed your latest comment, and keeping that in mind, there's a comprehensive guide on transitioning from JavaScript to TypeScript available in TS documentation here.

I'm also sharing two codesandbox examples, one involves a TS function utilized in JS with @ts-check and @ts-ignore annotations.
The second example incorporates JsDoc; without @ts-check activated, it doesn't undergo type checking. However, I've read about potentially enabling JsDoc typechecking by adding

"javascript.implicitProjectConfig.checkJs": true
to your vscode settings, although I lack personal experience with JsDoc.

Unfortunately, the alternatives seem limited to either converting necessary files to TS while setting accurate types (or resorting to typing everything as 'any' temporarily just to satisfy TS) or opting for @ts-check activation along with @ts-ignore preceding lines to avoid checking certain segments.

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

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

Is there a way to prevent a web page from automatically refreshing using JavaScript?

I would like my webpage to automatically refresh at regular intervals. However, if a user remains inactive for more than 5 minutes, I want the refreshing to stop. There is an example of this on http://codepen.io/tetonhiker/pen/gLeRmw. Currently, the page ...

What is the most effective method for enlarging elements using Javascript?

I have come across many different methods for expanding elements on webpages, such as using divs with javascript and jquery. I am curious to know what the most optimal and user-friendly approach is in terms of performance, among other things. For instance ...

What causes images to unexpectedly expand to fill the entire screen upon switching routes in Next.js?

I'm in the process of creating a website using Next and Typescript, with some interesting packages incorporated: Framer-motion for smooth page transitions Gsap for easy animations One issue I encountered was when setting images like this: <Link&g ...

Angular directive specifically meant for the parent element

I am working on a directive that I need to apply to a specific div element without affecting its child elements. The goal is to make the main div draggable, so that when it moves, its child divs move along with it. However, I do not want the child divs to ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

Is bower install failing to detect a local npm package?

After running bower install, I encountered the following error message: $ bower install module.js:340 throw err; ^ Error: Cannot find module 'minimist' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._l ...

Tips for executing gulp tasks in the command line

As a newcomer to Gulp, I've encountered an issue with executing a task named task1 in my gulp.js file. When I enter "gulp task1" in the command line, it opens the gulp.js file in Brackets editor instead of running the task as expected. Can anyone offe ...

What causes the error message "Irregular whitespace not permitted" and what are the solutions?

After using two <p> tags as shown in the code below, I encountered an error: "Irregular whitespace not allowed no-irregular-whitespace". How can I resolve this issue? <div> <p>Ankjjdhd asas a sds qwe vsdf fsf ewth lioy nfhfgh&l ...

Error message: "The term 'Outlet' is not recognized in react-router version 6.4"

What is the proper way to define the Outlet component in react-router version 6.4? Below is a code snippet: function Layout() { return ( <div> <Navbar /> <Outlet /> <Footer /> </div> ); } ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

The visual symbol is not being shown on the selection box in Mozilla Firefox

I've encountered an issue with a checkbox I created to display a + and - for expand and collapse functionality. HTML Code: <input type=checkbox class="ins" ng-model=show ng-class='{open:show}'><b>Show</b> CSS code: .ins ...

Issue encountered when trying to render Vue.js file with the view instance "new Vue()"

When working with vue.js and rendering a vue page, I encountered the following error: Error "Cannot GET /KForm" My code in main.js is as follows: import * as componentBase from "@app/app_start" import Form from "@views/Form/Form.vue" import KForm from ...

Utilize the event bus by calling `this.$root.$emit` command

I recently implemented a basic Event bus in my application to dynamically change styles on a page, and it's functioning correctly. The event bus is triggered using the $emit and $on methods as shown below: EventBus.$on and EventBus.$emit('call ...

What is the best way to dynamically assign a value to an anchor tag upon each click using jQuery?

How can I pass a value to an anchor tag on every click using jQuery? I am encountering an issue with my current code where the value is not being retrieved when I click the button. //HTML snippet <button id="a-selectNm" data-a_name="<?php echo $row[ ...

Retrieving input values with JQuery

HTML <td data-title="Quantity"> <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10"> <button class="btn-minus bg_tr d_block f_left" data-item-price="8000.0" data-direction= ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

Developing Webpart Postback logic in C# script

I am currently facing challenges with SharePoint webparts programming. I am unsure about how to trigger a postback for an object at a specific time. I have come across suggestions to use "javascript" for this purpose, but I am having trouble understanding ...

Issue with Node's jsonwebtoken library: jwt.sign() method fails to include payload in generated token

I am currently working on developing an API with Node.js and have configured const jwt = require('jsonwebtoken') to handle JWTs. However, I am facing an issue where the generated token does not contain the payload information. To troubleshoot thi ...

The Faux-Dynamic News Feed on a stationary website

As I work on revamping my employer's static website, it has become clear that a news section needs to be integrated. The site is being built using the Bootstrap 3.0 framework. My plan is to implement the following strategy: I aim to have a JavaScrip ...