0

I need to declare an array of objects, but unlike the other answers on StackOverflow my object is dynamic at runtime.

Example,

Possible [{"id":"1", "random1": "1", "random1": "1", "random1": "1"}]

Possible [{"id":"2", "p": "p2", "p2": "o2"}]

I have data: {}[] but where do I put the any?

const [data, setData] = useState({ data: {}[], isFetching: false });

Or can I define this in a way where I can say there will always be an id: string index but the rest can be any.

Something like this, which is not valid, but perhaps something like this is?

const [data, setData] = useState({ data: { [index: string]: any }[];, isFetching: false });

1 Answer 1

1

You can declare an auxiliary type, in order to specify your dynamic structure and keep your code clean:

type Data = {
  data: { [index: string]: any }[];
  isFetching: boolean;
}
// ...
useState<Data>({ data: [], isFetching: false });
// or
useState({ data: [], isFetching: false } as Data);

Given it is React, nothing stops you from having two states (but I suppose you don't like that given your actual code), like:

const [isFetching, setIsFetching] = useState(false);
const [data, setData] = useState([] as ({ [index: string]: any }[]));
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.