Daan
Daan

Reputation: 2799

How to set up Typescript with a React state with an Object?

I am new to TypeScript. I understand how to set up an interface for some types (I guess). But can't seem to grasp how the same would work with an Object type?

interface MyProps {
    defaultgreeting: 'Hello'
}

interface MyState {
    greeting: string
}

class MyApp extends Component<MyProps, MyState> {
    constructor(props: any) {
        super(props);
        this.state: {
            greeting: this.props.defaultgreeting
        }
    }
}

How would I have to set this up for the following state (which requires an Object)?:

this.state: {
    greeting: this.props.defaultgreeting,
    users: {
        name: 'John Doe',
        age: 25
    }
}

Upvotes: 4

Views: 5909

Answers (2)

DeeV
DeeV

Reputation: 36045

You have a couple options.

You can define the Users object within the MyState interface like so:

interface MyState {
    greeting: string;
    users: {
       name: string;
       age: number;
    }
}

Or, you can define the Users object somewhere else and assign it's type to the users attribute like this:

interface User {
   name: string;
   age: number;
}

interface MyState {
   greeting: string;
   users: User;
}

I usually prefer the second option because it lets you type the object by itself like:

const users: User = {
   name: "John Doe",
   age: 25
}

You can not do that with the first option. Although you can implicitly assign it:

interface MyState {
    greeting: string;
    users: {
       name: string;
       age: number;
    }
}

const users = {
   name: "John Doe",
   age: 25
}

const state: MyState = {
   greeting: "Hello",
   users
}

Upvotes: 6

hackape
hackape

Reputation: 20007

interface MyState {
    greeting: string;
    users: {
        name: string;
        age: number;
    }
}

Upvotes: 0

Related Questions