来自Typescript的意外错误,然后在PropTypes中使用形状

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

我声明了一个组件,并为其设置了类型React.FC<Props>propTypes,其中:

type Row = React.ReactElement[];

interface Header {
    value: string;
    title: string;
}

interface Props {
    headers: Header[];
    rows: Row[];
}
Table.propTypes = {
    headers: PropTypes.arrayOf(
        PropTypes.shape({
            value: PropTypes.string.isRequired,
            title: PropTypes.string.isRequired,
        }),
    ).isRequired,
    rows: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.element, PropTypes.string]))).isRequired,
};

我的IDE(PhpStorm)在header中给了propTypes下一条错误消息:

TS2322: Type 'Validator<InferProps<{ value: Validator<string>; title: Validator<string>; }>[]>' is not assignable to type 'Validator<Header[]>'.   Type 'InferProps<{ value: Validator<string>; title: Validator<string>; }>[]' is not assignable to type 'Header[]'.     Type 'InferProps<{ value: Validator<string>; title: Validator<string>; }>' is not assignable to type 'Header'.       Property 'value' is optional in type 'InferProps<{ value: Validator<string>; title: Validator<string>; }>' but required in type 'Header'.  Table.tsx(13, 2): The expected type comes from property 'headers' which is declared here on type 'WeakValidationMap<Props>'

以及rows

TS2322: Type 'Validator<(string | ReactElementLike)[][]>' is not assignable to type 'Validator<ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>[][]>'.   Type '(string | ReactElementLike)[][]' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>[][]'.     Type '(string | ReactElementLike)[]' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>[]'.       Type 'string | ReactElementLike' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>'.         Type 'string' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)>) | (new (props: any) => Component<any, any, any>)>'.  Table.tsx(14, 2): The expected type comes from property 'rows' which is declared here on type 'WeakValidationMap<Props>'

那么错误的原因是什么?我看到Props中的所有属性都是必需的,propTypes的所有属性都相同,但是打字稿说的不同。

reactjs typescript error-handling react-proptypes
1个回答
0
投票

我只会给自己正确的答案

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