DEV Community

YC Yap
YC Yap

Posted on • Updated on

[TIL] Typescript index signatures

I have recently encountered a problem while porting my toy react application from Javascript to Typescript, this toy-application , fetches all the popular repos from Github and displays them on the page.

The object looks something like this:

const [repos, setRepos ] = useState<{}>({})
{
'All': object,
'Ruby': object,
'Javascript: object
}

Problem arises when you try to access the repos object, Typescript compiler throws a type mismatch error. ( Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.)

repos[selectedLanguage] 

To solve this, i needed to define an interface in which any string can be as index for the object, it looks something like this.

interface Repos{
  [key: string]: object
}

Use the interface as the generic type for setState

const [repos, setRepos ] = useState<{Repos}>({})

And the problem goes away

repos[selectedLanguage] 

Top comments (0)