我知道如何在这种情况下推断类型:
import PropTypes from 'prop-types';
const props = {
id: PropTypes.number,
};
type Props = PropTypes.InferProps<typeof props>;
const x: Props = {};
x.id; // number | null | undefined
然而,在我的情况下,我有:
const propsShape = PropTypes.shape({
id: PropTypes.number,
// 更多包括嵌套的 PropTypes.shape 调用的属性
});
如果我尝试:
type PropsFromShape = PropTypes.InferProps<typeof propsShape>;
const y: PropsFromShape = {};
const z = y.id;
它无法编译:
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'.
我可以将 shape 的参数提取为一个单独的常量,并按上述方式进行操作,但是否有一种从 propsShape 直接推断属性类型的好方法?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要获取嵌套对象的类型,您可以使用
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);我个人认为后者更易读。