简体   繁体   中英

Using a component defined in a .jsx file in a typescript file

We have purchased a react theme with the intent to use its component in our web application, and we ended up with some issues getting them to transpile, we got that solved. However, we're now running into issues with types.

I believe the issue here is that typescript doesn't like that props doesn't have a type defined on it and is defaulting to IntrinsicAttributes. I'd like to be able to use the components without modification.

The error:

(TS) Property 'content' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Card> & Readonly<{ children?: ReactNode; }> & Read...'

home.tsx

import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import Card from './test';

type HomeProps = RouteComponentProps<{}>;

export default class Home extends React.Component<HomeProps, {}> {
    public render() {
        return <div>
            <Card content="but why doesn't this work?" />
        </div>
    }
}

test.jsx

import React, { Component } from 'react';


class Card extends Component {
    render() {
        return <div>
        {this.props.content}
        </div>;
    }

}
export default Card;

I think you are trying to create a new attribute, try creating a new interface for test file and define a interface in any of the typedefinition file as shown below,

interface Card {
     content: any;
}

Thanks

React defaults props and state to have the type {} , and this is why it claims content does not exist in this example.

Perhaps better than implementing the interface for each component is to do the following trick (which is not the prettiest):

In the .tsx file:

import OriginalCard from './test';

/* tslint:disable */
const Card: any = OriginalCard; 
/* tslint:enable */

And the you should be able to use Card without getting the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM