The Main Question
I seem to keep running into this in different forms in typescript. Sometimes a function, or some kind of object requires a specific interface, and I'm looking for a general set of steps to follow to figure out what those interfaces are.
Example Code
I'm trying to write a function that will iterate over the various colors of a Material-UI theme. I'm having trouble even accessing an individual one once I start passing parameters to do the job.
Working as expected
const printColor = () => {
const theme = createMuiTheme();
const color = theme.palette.primary['main'];
console.log(color);
};
printColor(); // prints #3f51b5 to the console
The failing example
const printColor = (key: string) => {
const theme = createMuiTheme();
const color = theme.palette.primary[key];
console.log(color);
};
printColor('main');
The error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PaletteColor'.
No index signature with a parameter of type 'string' was found on type 'PaletteColor'.
Further Thoughts
It seems as though I need to be adding some kind of type for the parameter key? I've been hunting around to try to figure out what type that would be. Why does this work when I access it directly as a string, and not when I pass it as a parameter?
Is there some way that you quickly determine which type to use when you run into these sorts of type errors?
Run The Code
As requested here's a link to play with the code yourself. https://stackblitz.com/edit/typescript-6rntqm
The code runs here, but only gives a warning. I think my tsconfig is just set to fail, but I'm trying to learn how to troubleshoot these things myself.
