I am working with a function that looks like this
interface Cat {
color: string,
weight: number,
cute: Boolean, // even though all cats are cute!
}
export const doSomething = (
cat: Array<Cat| null>,
index: number,
key: keyof typeof cat,
payload: string | number | Boolean
) => {
....
cat[key] = payload
....
}
As a result, I get the error message:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
This occurs because TypeScript is interpreting key
as any string instead of one of
"color", "weight", "cute"
.
How can I specify in the function declaration that key
should be one of these three values?
I attempted to use
...
key: keyof Cat,
...
but it did not work. Now, when I try to assign the value using
cat[key] = payload
I receive the following error:
Type 'string| number | Boolean | ' is not assignable to type '(string & number & Boolean )