Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is of type 'unknown' within .map?

I have a list of topics

const topics = getPromptCategories();

which looks like

[ { category: "cat1", attempts: 0 }, {category: "cat2", attempts: 0 } ]

So my interface is

interface topicInterface {
    category: string;
    attempts: number;
}

and I'm trying to derive a number of buttons out of the topics, so I'm doing this

const topicButtons = topics.map((topic) => {
    return <button>{topic.category}</button>;
});

but it's screaming at me about Object is of type 'unknown' at {topic.category}

If I add the interface to topic topic: topicInterface it's now telling me something different

Argument of type '(topic: topicInterface) => JSX.Element' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => Element'.

I'm new to typescript. What am I missing or overlooking?

like image 555
Mike Avatar asked Aug 31 '25 22:08

Mike


1 Answers

If it helps anyone else, @crashmstr pointed me in the right direction.

The issue was with my getPromptCategories() function as it wasn't returning topicInterface[].

I went into my function and adjusted my code to reflect this

let out: topicInterface[] = Object.values(...);
return out;

And my topicButtons looks like

const topicButtons = topics.map((topic:topicInterface) => {
    return <button key={topic.category}>{topic.category}</button>;
});
like image 180
Mike Avatar answered Sep 03 '25 19:09

Mike