React Typescript не распознает свойство 'type' дочернего элемента - PullRequest
1 голос
/ 14 марта 2019

Я пытаюсь получить доступ к displayName ребенка при использовании React.Children.map. Typescript, похоже, не распознает свойство type, которое находится на child. Однако, когда я просто console.log child, я вижу, что у него есть свойство type.

Я ссылаюсь на это руководство по созданию составных компонентов. Вот чего я хочу достичь (поэтому в настоящее время не работает):

<Card>
    <Card.Title>Title</Card.Title>
    <Card.Subtitle>Subtitle</Card.Subtitle>
    <Card.Body>Body</Card.Body>
    <Card.Footer>Footer</Card.Footer>
    <Card.Image src="assets/images/logo.png" />
</Card>

Это то, что у меня сейчас есть для Card компонента

import * as React from "react";
import { connect } from "react-redux";
import { ITheme } from "src/modules/CSS";

interface IState {
    theme: ITheme;
}

interface IProps extends IState {
    children: React.ReactNode;
}

const { Provider, Consumer } = React.createContext<IState | null>(null);

const Title = ({ children }: IProps) => (
    <Consumer>{() => <div>{children}</div>}</Consumer>
);

Title.displayName = "Title";

class Card extends React.Component<IProps> {
    constructor(props: IProps) {
        super(props);
    }

    public render() {
        const { children } = this.props;

        return (
            <Provider value={{ theme: this.props.theme }}>
                {React.Children.map(children, (child) => {
                    if (child) {
                        console.log(child.type.displayName); /* Property 'type' does not exist on type 'string | number | true | {} | ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | ReactNodeArray | ReactPortal' */
                    }
                    return child;
                })}
            </Provider>
        );
    }
}

const mapStateToProps = ({ theme }: IStoreState): IState => ({
    theme,
});

export default connect(mapStateToProps)(Card);

Когда я console.log: console.log(child)

РЕДАКТИРОВАТЬ: Вот мои tsconfig и tslint на случай, если это может повлиять на мою проблему: tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "allowJs": true,
        "jsx": "react",
        "sourceMap": true,
        "outDir": "./dist/",
        "removeComments": true,
        "strict": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "strictFunctionTypes": true,
        "strictPropertyInitialization": true,
        "noImplicitThis": true,
        "alwaysStrict": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "moduleResolution": "node",
        "baseUrl": ".",
        "resolveJsonModule": true,
        "paths": {
            "*": ["*", "types/*"]
        },
        "esModuleInterop": true
    },
    "exclude": ["node_modules", "**/*.spec.ts"]
}

tslint.json

{
    "defaultSeverity": "error",
    "extends": ["tslint:recommended"],
    "jsRules": {},
    "rules": {
        "arrow-return-shorthand": [true, "multiline"],
        "object-literal-sort-keys": false,
        "no-console": false
    },
    "rulesDirectory": []
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...