Reproducing the issue
The function setTextColor takes a string color as an argument, looks up that string in the textColors object, and returns the corresponding color value. The issue with the following code is that the color argument in the setTextColor function is typed as string, which allows any string to be passed, but the textColors object only accepts specific keys (primary, secondary, info).
const textColors = {
primary: "black",
secondary: '#eee',
info: 'blue'
};
function setTextColor(color: string) {
return textColors[color];
}
console.log(setTextColor('info'));
Error
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ primary: string; secondary: string; info: string; }'.
No index signature with a parameter of type 'string' was found on type '{ primary: string; secondary: string; info: string; }'.(7053)
Solution
Limit the color argument to the valid keys of textColors using keyof typeof textColors, so only the allowed color names can be used.
const textColors = {
primary: "black",
secondary: '#eee',
info: 'blue'
};
type textColorType = keyof typeof textColors;
function setTextColor(color: textColorType) {
return textColors[color];
}
console.log(setTextColor('info')); // output: 'blue'
Summary
Using keyof and typeof together creates a union type from the object’s keys. This means that only strings matching the keys (like "primary", "secondary", and "info" from textColors) can be passed as arguments, ensuring type safety.