Utilizing TypeScript JSDoc notations for managing React PropTypes

When creating react components with TypeScript, we typically declare them like this:

class SomeComponent extends React.Component<PropInterface, StateInterface> {
  // ...
}

Is it possible to achieve the same prop type-checking functionality using JSDoc annotations?

Answer №1

I like to use the following format (es2015 + @types/react):

/**
 * @typedef {object} Props
 * @prop {string} className
 * @prop {number} numberProp
 *
 * @extends {Component<Props>}
 */
export default class SomeComponent extends Component {
    render() {
        return (
            <div className={this.props.className}>
                {this.props.numberProp}
            </div>
        );
    }

}

Answer №2

If you're in need of an alternative solution, consider the following approach. For more information on this Typescript issue, check out the provided link.

import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * @augments {Component<{onSubmit:function, text:string}>}
 * @param {object} event - Input event
 * @return {React.ReactElement} - React component
*/
class Test extends Component {
  handleInput = (event) => {
    event.preventDefault();
    this.props.onSubmit(event.target.value);
  };

  render() {
    const { text } = this.props;
    return <div>Hello, property :O {text}</div>;
  }
}

Test.propTypes = {
  onSubmit: PropTypes.func.isRequired,
  text: PropTypes.string.isRequired,
};

export default Test;

Answer №3

While this solution functions, its effectiveness may vary.

// Bar.jsx
import * as React from 'react';

/**
 * @type {{ new(props: any): {
     props: { x: string, y: number },
     state: any,
     context: any,
     refs: any,
     render: any,
     setState: any,
     forceUpdate: any
   } }}
 */
const Bar = class Bar extends React.Component {
  render() {
    return <div className={this.props.x}>{this.props.y}</div>;
  }
};
export default Bar;

// import Bar and utilize it in .tsx or .jsx file
import Bar from './Bar';

<Bar/>; // error: Type '{}' is not assignable to type '{ x: string; y: number; }'
<Bar x='x' y={0}/>; // OK

Answer №4

If you are utilizing PropTypes in your React application,

you can try implementing it like this:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * Example component with PropTypes
 * @augments {Component<Props, State>}
 */
class ExampleComponent extends React.Component {
  // ...
}

ExampleComponent.propTypes = {
  title: PropTypes.string.isRequired,
}

export default class AnotherComponent extends React.Component {
  render() {
    return <ExampleComponent  />
  }
}

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

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

Utilizing amCharts Postprocessing for fetching data for visual representation

My goal is to utilize amcharts for displaying data retrieved from my server. Unfortunately, the API format doesn't align directly with amCharts. It seems that I need to utilize the postProcess function to preprocess the data, but I am struggling due t ...

Changing the .load function based on user input

Can I replace a .load text with one that can be updated by a user using form input or similar method? My goal is to create a code that retrieves data using unique div IDs (specific to each employee) containing information within tables across various HTML ...

The geolocation feature is operational in the browser test, but it is not functioning properly on the

I am currently creating an application that requires accessing the user's location at a specific point in time. To achieve this, I have utilized the ionic native geolocation feature which communicates with the Google API for reverse geocoding. Everyt ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

How can I invoke a TypeScript function within HTML code?

Currently, I am working on an Angular project where I have implemented two straightforward methods in a TypeScript file: findForm(text: string, forms: Array<string>) { for (let form of this.forms) { if (text.includes(form)) { retur ...

What is the best way to add elements using JavaScript when a particular character is present?

Current: <p id="article">忙著端出 高階 DSLR 產品的 Nikon ,總算想到了在 兩年半之後 更新自己的入門系列數位單眼相機,端出 Nikon D3400。很好的產品</p> I want to divide the text whenever certain charac ...

Displaying results as you scroll down within a container

I want to create a feature similar to Facebook where more results are loaded when the page is scrolled down. I need to style both an outer and inner div for this implementation. .Outer{ height: 1430px; margin-top: -12px; overflow: hidd ...

What is the best way to set up a list of states in React using hooks?

Suppose I have a variable, n, which can take on any value. My objective is to generate n input fields while maintaining the state of each input. However, I am currently facing challenges in figuring out how to achieve this. For instance, when n = 3, my des ...

Retrieve a targeted data value from a JSON object based on an array value

Looking at the JSON array and another array provided below. JSON OBJECT { id: 1, name: 'abc', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbebdbc9fb8b2beb6b3f1bcb0b2">[emai ...

The Select2 ajax process runs twice

I am encountering an issue with a script I have that retrieves data from the backend to populate a select2 dropdown. The problem is that the ajax call is being triggered twice every time, which is not the desired behavior. I'm unsure of what mistake I ...

Encountered difficulties implementing Chart.js with Angular2

Greetings! I am currently attempting to utilize one of the Charts provided by http://www.chartjs.org, however, I seem to be encountering difficulties in getting it to function properly. I have followed the documentation by installing 'npm install char ...

Guide to successfully submitting an Angular form that includes a nested component

I have developed a custom dateTime component for my application. I am currently facing an issue where I need to integrate this component within a formGroup in a separate component. Despite several attempts, I am unable to display the data from the child fo ...

Firestore emulator outperforms Firestore in terms of performance

My application is capable of handling a substantial volume of write, read, and update operations (potentially exceeding 10000) under specific conditions. During the development of the app on a local environment, these operations usually complete within a ...

The shiny conditional panel fails to evaluate upon initialization

When utilizing conditional panels to dynamically build up my Shiny app, I've noticed that the condition the panel is based on is not initially evaluated. The panel remains visible by default and only becomes hidden after certain actions are taken. Thi ...

Sending error messages from server to client (leveraging Express and Backbone)

I'm struggling with passing server error messages to a client after thrashing around for a while. Here's what I have on the server side (simplified): export function get(req: express.ExpressServerRequest, res: express.ExpressServerResponse) { ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

Utilizing underscores to assign values as keys in a minimized object

After some tinkering, I successfully streamlined my Price Amount Object by combining it like so: stooges = [{Price: 1.2, Amount: 40}, {Price: 1.3, Amount: 50}, {Price: 1.2, Amount: 60}]; inputarray = _.map _.groupBy(stooges, 'Price'), (v, k) - ...

"Enhancing user experience: Downloading content as a PDF file with ReactJS in a web

I need assistance with providing a downloadable link for invoices. I save all the invoices in an array and when a user clicks on a particular invoice, it should download in the browser while keeping track using an index number. However, I am encountering a ...

Managing "post" requests in a one-page web application using node.js

Although there may be similar answers to this question, I am in search of something different. On the client side, I have a signUp form that will make a post request to the server with the username and password. On the server side, I authenticate the req ...

Creating CSS for a specific class on a single webpage can be achieved by targeting that class

Here is my custom style: <style> ul { padding:0 0 0 0; margin:0 0 0 0; } ul li { list-style:none; margin-bottom:25px; } ul li img { cursor: poin ...