Search code examples
javascriptreactjstypescripttypescript2.0

Typescript error : No index signature with a parameter of type 'string' was found on type '{}'


Hi I am new to Typescript and I don't know how to solve a typescript error : No index signature with a parameter of type 'string' was found on type '{}'.. I've read some SO post about I haven't been able to understand this error and how to best solve it. Any help and explanation why I have this error would be appreciated.

TypeScript error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.

52 | caseValue={covidData[caseLabel].value}
                ^
53 | lastUpdate={covidData['lastUpdate']}
                ^

covidData Object

enter image description here

My Component


import React from 'react';
import { Grid } from '@material-ui/core';

import { Cards, Chart, CountryPicker } from './components/index';
import styles from './App.module.scss';
import { fetchData } from './api';

interface CovidDataNestObjectType {
    value: number
}

type State = {
    country: string,
    covidData: {
        [key: string] : CovidDataNestObjectType,
    }
}

class App extends React.Component<State> {
    state = {
        covidData: {},
        country: '',
    };

    async componentDidMount() {
        const fetchedData = await fetchData();
        this.setState({ covidData: fetchedData });
}

    render() {
        const { covidData, country } = this.state;

        return (
            <div className={styles.container}>
                <Grid container spacing={3} justify='center'>
                    {covidData &&
                        Object.keys(covidData).map((caseLabel: string, i) => (
                            <Cards
                                key={i}
                                caseLabel={caseLabel}
                                caseValue={covidData[caseLabel].value} // error
                                lastUpdate={covidData['lastUpdate']} // error
                            />
                        ))}
                </Grid>
                <Chart country={country} covidData={covidData} />
            </div>
        );
    }
}

export default App;





Solution

  • Try this in your class

    state: State = {
            covidData: {},
            country: ''
        };