0

Hi I have this complex object and I need to create a type or interface for it in my react --typescript-template app

const columnsFromBackend = {
  ["0"]: {
    name: "Terminator Group",
    items: [
      {
        filepath: "0.jpg",
        group: "terminator",
        id: "0",
        isClicked: false,
        title: "image_0",
      },
      {
        filepath: "1.jpg",
        group: "terminator",
        id: "1",
        isClicked: false,
        title: "image_1",
      },
     ]
   }
}

I have tried this

export type Character = {
    name: string;
    items: {
      filepath: string;
      group: string;
      id: string;
      isClicked: boolean;
    }
  xxxxxxx
  const [columns, setColumns] = useState<Character{}>(columnsFromBackend);

but it didn't work?

1
  • @NatalieMae's answer should have you covered. But you probably also want an array of characters for you state. useState<Character[]>. [] not {}. Commented Aug 2, 2022 at 0:12

1 Answer 1

1

You have defined your items only as an object rather than an array of objects.

Try:

export type CharacterItem = {
    filepath: string;
    group: string;
    id: string;
    isClicked: boolean;
   }

export type Character = {
    name: string;
   items: CharacterItem[]
   }

Or something similar!

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

3 Comments

Array<CharacterItem/> is invalid syntax. You probably meant Array<CharacterItem>. Although, CharacterItem[] is probably more common.
I sure did! I've been playing with TSX too much! Thanks pal!
thank you, however, its still lenting red line underneath columnsFromBackend as in const [columns, setColumns] = useState<Character[]>(columnsFromBackend); with this error message ``` Argument of type '{ 0: { name: string; items: { filepath: string; group: string; id: string; isClicked: boolean; title: string; }[]; }; 1: { name: string; items: { filepath: string; group: string; id: string; isClicked: boolean; title: string; }[]; }; }' is not assignable to parameter of type 'Character[] | (() => Character[])'.ts(2345) ```

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.