P粉8721016732023-08-15 09:53:53
To get the type of a nested object, you can use 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;
Alternatively, if you can put the entire props definition in one place:
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);
I personally think the latter is more readable.