Home > other >  Argument of type is not assignable to parameter of type Typescript Error
Argument of type is not assignable to parameter of type Typescript Error

Time:03-15

I try to map this object in HTML

enter image description here

This is the code in React component:

return (
        <Wrapper>
            <div className="album py-5 bg-light">
                <div className="container">
                    <div className="table-responsive">
                        <table className="table table-striped table-sm">
                            <thead>
                            <tr>
                                <th>#</th>
                                <th>Name</th>
                                <th>Revenue</th>
                            </tr>
                            </thead>
                            <tbody>
                            {Object.keys(rankings).map((r: { name:string, revenue:number }, index) => {
                                return (
                                    <tr key={index}>
                                        <td>{index   1}</td>
                                        <td>{r.name}</td>
                                        <td>{r.revenue}</td>
                                    </tr>
                                );
                            })}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </Wrapper>
    );
};

For some reason I get error:

Argument of type '(r: { name: string; revenue: number; }, index: number) => Element' is not assignable to parameter of type '(value: string, index: number, array: string[]) => Element'.
Types of parameters 'r' and 'value' are incompatible.
Type 'string' is not assignable to type '{ name: string; revenue: number; }'.  TS2345

Do I make some syntax mistake or is is something else?

CodePudding user response:

Your issue lies on how you're mapping the rankings object.

You should replace it like this:

Object.keys(rankings).map((name, index) => {
    const revenue = rankings[name];         
    return (
        <tr key={index}>
            <td>{index   1}</td>
            <td>{name}</td>
            <td>{revenue}</td>
        </tr>
    );
})

Keep in mind that Object.keys(obj) returns an array of the keys from the obj object. You're trying to consume that function as if it was returning an array of {name, revenue} objects.

  • Related