Rumah > Soal Jawab > teks badan
P粉8721016732023-08-15 09:53:53
Untuk dapatkan jenis objek bersarang boleh gunakan 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;
Atau jika anda boleh meletakkan keseluruhan definisi prop di satu tempat:
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);
Saya secara peribadi berpendapat yang kedua lebih mudah dibaca.