0

I'm trying to get myself familiarized with react.js with typescript. I tried to declare a Array of JSON, but it gives me error saying ... is not assignable to JSON

Here is my code:

import React from 'react';
type MyProps = {
    message?: string;
};
type MyState = {
    chat_list : Array<JSON>
    count: number; // like this
};
class ChatList extends React.Component<MyProps, MyState> {
    state: MyState = {
        count: 0,
        chat_list : [
            {
                "name":"true",
                "active" : true
            }
        ]
    };
    ...

How can I resolve this?

1 Answer 1

3

You should define the shape of a chat item, JSON is an actual global object with a specific shape (JSON.stringify, JSON.parse etc)

    interface ChatItem {
      name: string;
      active: boolean;
    }

    interface MyState {
      chat_list: Array<ChatItem>; // Or ChatItem[]
      count: number;
    }

   state: MyState = {
      count: 0,
      chat_list: [
        {
          name: 'true',
          active: true,
        },
      ],
    };
Sign up to request clarification or add additional context in comments.

5 Comments

thanks it worked, out of curiosity just asking, instead of declaring an interface can I use a per-declared class ?? cause I already have one class alternative to ChatItem as ChatListItem
Not sure what you mean by per declared class? As in define something just for the class? The interface or type can be scoped to inside a function or file if that's what you mean
i tried to mean pre-declared class, I want access it from all of my classes ..
just decalare in an another file, or better way, something like declaring as props or something , new to react-typescript
yeah for shared types I recommend you have a file like types.ts and import from there, which also avoids circular dependency issues. There are also "ambient declaration files" alternatively but I think simpler to stick to that.

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.