1
interface User {
  name: string,
  address: string,
  active: boolean
}

The problem is -

I can't import interface in child component. Child component interface have to be the type parent component provided. So how can I access component props to define interface.

1
  • 2
    It's unclear what your problem is. Give a minimal reproducible example of child and parent and show the error. Commented Aug 25, 2020 at 18:57

2 Answers 2

4

The interface that need to be imported need to be explicitly exported from the file where it is declared.

Here is the working example for exporting an interface and importing it in a component:

Interface file - IUser.ts

// File name: IUser.ts

export interface IUser {
  name: string,
  address: string,
  active: boolean
}

Component File - Functional comopnent / React Hook

// File name: MyComponent.tsx

import React, {FunctionComponent} from 'react'
import {IUser} from "../interfaces/IUser"


const MyComponent : FunctionComponent<IUser> = (props) => (
    <div>
        <div>Name: {props.name}</h2>
        <div>Address: {props.address}</div>
        <div>Active: {props.active}</div>
    </div>
)

export default MyComponent

Component File using Class

// File name: MyComponent.tsx

import React, {Component} from 'react'
import {IUser} from "../interfaces/IUser"

export default class MyComponent extends Component<IUser> {
    render() {
        return (
            <div>
                <div>Name: {this.props.name}</h2>
                <div>Address: {this.props.address}</div>
                <div>Active: {this.props.active}</div>
            </div>
        )
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

first you should export your interface like so:

export interface User {
name: string,
address: string,
active: boolean
}

then you can import it wherever you want:

import { User } from 'relative/path/to/interface'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.