0

I have an Object named Parent and it has an array of another object named Child and I dont know how to give its initial value when called in state of a component class. I tried to casting it with as Child[] but it still doesn't work

Parent :

export interface Parent {
    id: string,
    child : Child[]
}

State in Component

interface State {
    parent: Parent
}

How I initialize the value

constructor(props: Props) {
    super(props);
    this.state = {
        parent: {
            id: "",
            child: [] as Child[]
        }
    }
}

Thank You.

1
  • What you have is correct, and the as Child[] is unecessary. Commented Jun 10, 2020 at 10:53

1 Answer 1

1

You can define the type of your state in class definition:

View in the TypeScript Playground


export interface Parent {
    id: string,
    child : Child[]
}
interface State {
    parent: Parent
}
interface Props {
}

class MyComponent extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {
            parent: {
                id: "",
                child: []  // you don't have to define type 
                           // typescript infers State interface in this.state
            }
        }
    }


    render() {
        return (<div>...</div>)
    }

}

Within TypeScript, React.Component is a generic type (aka React.Component), so you want to provide it with (optional) prop and state type parameters:

Read more in typescript-cheatsheet

Sign up to request clarification or add additional context in comments.

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.