简体   繁体   中英

WebStorm type checking React props using type definition

I'm using WebStorm 2018.3.4 and am trying to figure out how to do type checking on a React component's props. Specifically, if a prop is marked as a string but I give it a number I want WebStorm to show an error. I've created a type definition file (as described here ). Here's what the file looks like:

MyComponent.d.ts

import * as React from 'react';

export interface MyComponentProps {
  /** this is the component's title */
  title: string;

  /** this is a short description of the component */
  description?: string;
}

declare class MyComponent extends React.Component<MyComponentProps, {}> {
  render(): JSX.Element;
}

export default MyComponent;

App.jsx

class App extends React.Component {
  render() {
    return (
      <MyComponent title={7} />
    );
  }
}

I was hoping WebStorm would underline title={7} telling me that 7 is the wrong type. If I Ctrl+Q on the prop it definitely tells me the type is string and it gives me the documentation from the .d.ts file. Is there a setting I need to enable? Or does WebStorm not support this? Or is my problem that my app is using JSX rather than TypeScript? Any help would be appreciated.

You can install prop-types

Then you can write your component like this:

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

class App extends Component {
    static propTypes = {
        userId: PropTypes.string.isRequired,
        someObject: PropTypes.object.isRequired,
        someFunction: PropTypes.func.isRequired,
    };

    render() {
       ....
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM