Emmanuel okpani
Emmanuel okpani

Reputation: 11

Element implicitly has an 'any' type because expression of type '`${any}`' can't be used to index type

I missed out something here using Typescript I need help

   const onClick = (name: string) => {
      dialogFuncMap[`${name}`](true);
    };

    const onHide = (name: string) => {
      dialogFuncMap[`${name}:any`](false);
    };

Upvotes: 1

Views: 57

Answers (1)

lepsch
lepsch

Reputation: 10319

Solution 1

The following should work. The key is to declare name as the keys of dialogFuncMap instead of just string. This is because the type associated with dialogFuncMap has predefined indexes and their type should be the same. Notice now name is declared as name: DialogFuncMapKeys.

const hello = (value: boolean) => console.log('hello')
const world = (value: boolean) => console.log('world')

const dialogFuncMap = {
  hello: hello,
  world: world,
}

type DialogFuncMapKeys = keyof typeof dialogFuncMap // <- Here

const onClick = (name: DialogFuncMapKeys) => { // <- Here
  dialogFuncMap[`${name}`](true)
}

const onHide = (name: DialogFuncMapKeys) => { // <- Here
  dialogFuncMap[`${name}`](false)
}

onClick('hello')
onHide('world')

Solution 2

Another solution is to declare the dialogFuncMap keys themselves type as string like Record<string, (value: boolean) => void>. Take a look below:

const hello = (value: boolean) => console.log('hello')
const world = (value: boolean) => console.log('world')

const dialogFuncMap: Record<string, (value: boolean) => void> = { // <- Here
  hello: hello,
  world: world,
}

const onClick = (name: string) => {
  dialogFuncMap[`${name}`](true)
}

const onHide = (name: string) => {
  dialogFuncMap[`${name}`](false)
}

onClick('hello')
onHide('world')

Upvotes: 1

Related Questions