搜索

首页  >  问答  >  正文

能否根据 PropTypes 推断 TypeScript 中的类型?

<p>我知道如何在这种情况下推断类型:</p> <pre class="brush:php;toolbar:false;">import PropTypes from 'prop-types'; const props = { id: PropTypes.number, }; type Props = PropTypes.InferProps<typeof props>; const x: Props = {}; x.id; // number | null | undefined</pre> <p>然而,在我的情况下,我有:</p> <pre class="brush:php;toolbar:false;">const propsShape = PropTypes.shape({ id: PropTypes.number, // 更多包括嵌套的 PropTypes.shape 调用的属性 });</pre> <p>如果我尝试:</p> <pre class="brush:php;toolbar:false;">type PropsFromShape = PropTypes.InferProps<typeof propsShape>; const y: PropsFromShape = {}; const z = y.id;</pre> <p>它无法编译:</p> <pre class="brush:php;toolbar:false;">Type '{}' is not assignable to type 'PropsFromShape'. Property 'isRequired' is missing in type '{}' but required in type 'InferPropsInner<Pick<Requireable<InferProps<{ id: Requireable<number>; }>>, "isRequired">>'. Property 'id' does not exist on type 'PropsFromShape'.</pre> <p>我可以将 <code>shape</code> 的参数提取为一个单独的常量,并按上述方式进行操作,但是否有一种从 <code>propsShape</code> 直接推断属性类型的好方法?</p>
P粉715304239P粉715304239553 天前545

全部回复(1)我来回复

  • P粉872101673

    P粉8721016732023-08-15 09:53:53

    要获取嵌套对象的类型,您可以使用type NestedProps = PropTypes.InferProps<typeof propsShape>['isRequired'];

    import PropTypes from "prop-types";
    
    const propsShape = PropTypes.shape({
      nestedId: PropTypes.number,
      // 更多包括嵌套的PropTypes.shape调用的属性
    });
    
    const props = {
      id: PropTypes.number,
      optionalWithShape: propsShape
    };
    
    type Props = PropTypes.InferProps<typeof props>;
    type NestedProps = PropTypes.InferProps<typeof propsShape>['isRequired'];
    
    const x: Props = {};
    x.id = 1;
    
    const y: NestedProps = {
      nestedId: 1
    }
    
    x.optionalWithShape = y;

    或者,如果您可以将整个props定义放在一个地方:

    import PropTypes from "prop-types";
    
    const props = {
      id: PropTypes.number,
      optionalWithShape: PropTypes.shape({
        nestedId: PropTypes.number
      })
    };
    
    type Props = PropTypes.InferProps<typeof props>;
    type NestedProps = Props['optionalWithShape'];
    
    const x: Props = {};
    x.id = 1;
    
    const y: NestedProps = {
      nestedId: 1
    }
    
    x.optionalWithShape = y;
    
    console.log(x.optionalWithShape.nestedId);

    我个人认为后者更易读。

    回复
    0
  • 取消回复