Heim > Fragen und Antworten > Hauptteil
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);
我个人认为后者更易读。