如何为键入的React组件属性获取代码完成?

sto*_*fln 12 javascript reactjs mobx-state-tree

我正在使用react和mobx-state-tree,并且@inject用于将商店注入到我的组件中。所以最后,我通过this.props.uiStore组件内部访问商店。

不幸的是,Visual Studio Code无法推断我的商店的类型,因此我没有属性的任何代码完成。我想知道是否可以使用jsDoc它(因为它可以很好地用于方法),但是找不到方法。我在想一些类似的事情:

export default class DeviceMirror extends React.Component {
  /**
   * @namespace
   * @property {object}  props
   * @property {UiStore}  props.uiStore
   */
  props
Run Code Online (Sandbox Code Playgroud)

但这行不通。

rem*_*x23 5

您可以使用JSDoc来使Visual Studio Code正确地推断React组件的道具,诀窍是使用@extends {Component<{type def for props}, {type def for state}>}}

文件:store.js(这只是一个示例文件,用于演示intellinsense如何捕获定义,但是任何对象,类,typedefiniton甚至可能是json都可以。如果可以导入并反映它,则可以将其链接到组件道具)

    class CustomClass {
        // ...
    }
    // Note: exporting an object would also do
    export default class UiStore {
        /**
         * @type {string} this is a string
         */
        str = null
        /**
         * @type {number} this is a number
         */
        num = null
        /**
         * @type {Date} this is a Date
         */
        dat = Date
        /**
         * @type {CustomClass} this is a CustomClass
         */
        cls = null
    }
Run Code Online (Sandbox Code Playgroud)

文件:test.jsx

    import React, { Component } from 'react';
    import PropTypes from 'prop-types';
    import UiStore from './store';

    /**
     * @typedef Props
     * @prop {UiStore} uiStore
     */

    /**
     * @extends {Component<Props, {}>}}
     */
    export default class DeviceMirror extends Component {
        static propTypes = {
            // not needed for intellisense but prop validation does not hurt
            uiStore: PropTypes.instanceOf(UiStore),
        }
        /**
         * @param {Props} props - needed only when you don't write this.props....
         */
        constructor(props) {
            super(props);
            this.s = props.uiStore.str;
        }
        render() {
            const { uiStore } = this.props;
            return <p>{uiStore.str}</p>;
        }
    }

Run Code Online (Sandbox Code Playgroud)

VSCode可以使用这种声明,并提供智能感知和代码完成功能。从组件文件的内部和外部:

vscode的屏幕截图


vic*_*nyy 3

无法从 TypeScript 类型声明转到 mobx-state-tree 模型定义。但是,如果您编写 mobx-state-tree 模型定义,那么您可以从中生成 TypeScript 类型;使用 MST类型。因此,您必须转换现有的接口,但至少您不必保留相同信息的两个副本。

import { types, Instance } from 'mobx-state-tree';

const uiStore = types.model({
  prop: types.string,
});
export type IuiStore = Instance<typeof uiStore>;

export default uiStore;
Run Code Online (Sandbox Code Playgroud)