Leverage TypeScript exclusively for type-checking JavaScript code with JSDoc annotations

I am looking to incorporate types in an existing JS project specifically for IDE syntax highlighting, without adding to the library @types/.

For example, I have a file named 'TestComponent.js':

export const TestComponent = (props) => {
    return <div>{props.someString}</div>;
};

In order to declare types, I created a file 'TestComponent.d.ts':

interface TestComponentProps {
    someString: string;
}

export type TestComponent = (props: TestComponentProps) => JSX.Element;

I also added a JSDoc type to 'TestComponent.js':

/** @type {import('./TestComponent').TestComponent} */
export const TestComponent = (props) => {
    return <div>{props.someString}</div>;
};

As a result, VSCode now highlights props as an object with the key 'someString'.

Is it acceptable to use Typescript solely for this purpose?

While I am aware I could stick with JSDoc, I am not a fan of its syntax. Are there any better solutions for this?

Answer №1

Absolutely, it is totally acceptable. I suggest defining types directly within the JavaScript files, especially since interfaces in JSDocs are not fully supported. The rationale behind this is that even though it's permissible to include TypeScript files (which your application will disregard), it's best to avoid having an excessive amount of them to prevent chaos as your application expands.

Therefore, my recommendation is to utilize JSdocs (the TypeScript version when possible) within your JavaScript files. In instances where you cannot or require intricate types or specialized cases, opt for TypeScript files instead.

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

The "shape" property is not available while utilizing generics with toZod

Short version: I encountered a type error, and here is the link to the TS PLAYGROUND I am looking to ensure type safety when creating zod schemas. To achieve this, I define the data type like so: type Option = { id: number }; Using this type definition ...

AOT compile error due to Angular interpolation syntax

I am facing an issue while compiling my application. The AOT compiler is showing an error related to Angular interpolation in an Angular 2 form: Property 'address' does not exist on type 'FirebaseObjectObservable'. Here's a sn ...

The mat-table fails to populate with data retrieved from the rest service

I have successfully fetched an array from my REST service and displayed some information from the response on the page. However, I am facing issues populating my mat-table and I'm unsure of the cause. The mat-table was functioning properly in the past ...

Tips for integrating JavaScript libraries into TypeScript build process in Visual Studio

Is it possible to configure the "TypeScript Build" feature in Visual Studio 2017 to include both Javascript libraries and TypeScript files in the generated bundle.js output? ...

Using MUI DatePicker and react-hook-form to implement a date picker in the format DD/MM/YYYY

I have developed a custom datePicker component that combines react-hook-form and Material UI. However, I am encountering an issue where the values are being displayed in the format: "2024-04-10T22:00:00.000Z" Below is the code snippet: import { Localizati ...

Is there a way to define type information for a global variable when utilizing dynamic import within a function?

Here is a simplified version of my server code: server.ts import google from "googleapis"; const androidPublisher = google.androidpublisher("v3"); app.use('something', function(req, res, n){ ... }) ...(only one of the dozens of other meth ...

Children components are not re-rendered by React

I created a basic task manager, but I'm encountering issues when trying to manage all the data from a single point within the TaskManager component. Essentially, I have a TaskManager component that acts as the container for all the data. Within this ...

What is the best way to retrieve entire (selected) objects from a multiselect feature in Angular?

I'm facing an issue with extracting entire objects from a multiselect dropdown that I have included in my angular template. Although I am able to successfully retrieve IDs, I am struggling to fetch the complete object. Instead, in the console, it dis ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Mapping intricate entities to intricate DTOs using NestJS and TypeORM

Currently, I am using the class-transformer's plainToClass(entity, DTO) function to transform entities into DTO objects. In addition, I have implemented the transform.interceptor pattern as outlined in this source. I make use of @Expose() on propert ...

Simulate internationalization for vue using jest

Currently, I am working on setting up jest unit tests for a Vue project within a complex custom monorepo. I am facing an issue with i18n, which I use for translation management in my application. The problem arises with the following code snippet for init ...

Creating bonds between components in React

As a newcomer to React JS, I am exploring how to implement event listeners in VanJS. For organizing my layout, I have decided to create separate components for elements like a panel and a button. Now, I am faced with the challenge of triggering a state c ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Extending Record in Typescript: A Comprehensive Guide

When working on interfaces, I often find myself wanting to extend the type Record in order to define objects with predefined keys and optional values without knowing their names. For instance: interface Person extends Record<string, string>{ phonen ...

What is the proper way to define a generic function that accepts a Union type as an argument?

I am dealing with various types and their unions. Here is the code snippet: type A = { name: string } type B = { work: boolean } type AB = A[] | B[] const func = (): AB => { return [{ name: 'ww' }] } const data = ...

Tips for efficiently resolving and compiling a bug within an NPM package, ensuring it is accessible to the build server

This question may seem a bit unconventional. I am currently using an npm package that includes built-in type definitions for TypeScript. However, I have discovered a bug in these definitions that I am able to easily fix. My goal is to make this updated ve ...

A long error occurred while using the payloadaction feature of the Redux Toolkit

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit" import axios, { AxiosError} from "axios" type user = { id: number, token: string } export type error = { error: string } interface authState { user: user | ...

Leveraging $sceDelegateProvider for allowing Youtube in Typescript

I'm currently facing an issue with my app where I am trying to enable users to input Youtube URLs for videos to be displayed on the site. However, before implementing this feature, I need to whitelist Youtube. How can I adjust my typescript file (app. ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...