Reputation: 11
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
Reputation: 10319
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')
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