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);
我個人認為後者比較易讀。