【问题标题】:WebStorm type checking React props using type definition使用类型定义的 WebStorm 类型检查 React 道具
【发布时间】:2019-02-26 15:47:40
【问题描述】:

我正在使用 WebStorm 2018.3.4 并试图弄清楚如何对 React 组件的 props 进行类型检查。具体来说,如果一个道具被标记为 string 但我给它一个 number 我希望 WebStorm 显示错误。我创建了一个类型定义文件(如here 所述)。文件如下所示:

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} />
    );
  }
}

我希望 WebStorm 会在 title={7} 下划线,告诉我 7 是错误的类型。如果我在道具上Ctrl+Q,它肯定会告诉我类型是string,它给了我来自.d.ts 文件的文档。有没有我需要启用的设置?或者 WebStorm 不支持这个?或者我的问题是我的应用程序使用的是 JSX 而不是 TypeScript?任何帮助将不胜感激。

【问题讨论】:

  • Webstorm 不提供道具类型检查(即它不报告类型不匹配)。如果您错过了此功能,请向 youtrack 提出功能请求,youtrack.jetbrains.com/issues/WEB
  • 谢谢@lena!我就是这么想的,只是想确认一下。

标签: reactjs typescript webstorm tsd


【解决方案1】:

你可以安装prop-types

然后你可以这样写你的组件:

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() {
       ....
    }
}

【讨论】:

  • 这绝对适用于所需的道具,但如果给定道具的类型与定义的不同,WebStorm 不会发出警告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 2021-01-27
  • 1970-01-01
相关资源
最近更新 更多