我可以从 PropTypes 形状推断 TypeScript 类型吗?

问题描述 投票:0回答:1

我知道如何在这种情况下推断类型:

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,
  // more properties including nested PropTypes.shape calls
});

如果我尝试

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
推断属性类型?

reactjs typescript react-proptypes
1个回答
1
投票

要获取嵌套对象的类型,可以使用

type NestedProps = PropTypes.InferProps<typeof propsShape>['isRequired'];

import PropTypes from "prop-types";

const propsShape = PropTypes.shape({
  nestedId: PropTypes.number,
  // more properties including nested PropTypes.shape calls
});

const props = {
  id: PropTypes.number,
  optionalWithShape: propsShape
};

type Props = PropTypes.InferProps<typeof props>;

const x: Props = {};
x.id = 1;

type NestedProps = PropTypes.InferProps<typeof propsShape>['isRequired'];

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);

后者读起来更好恕我直言。

© www.soinside.com 2019 - 2024. All rights reserved.