(irrelevant code removed for demo purposes)
I am new to using TypeScript and I have this React component which has an object literal inside the component, which I'm then accessing using a computed property key. Everything works as expected but I was getting the following TS error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ keyword: string; hex: string; rgb: string; }'.
No index signature with a parameter of type 'string' was found on type '{ keyword: string; hex: string; rgb: string; }'.ts(7053)
I managed to get rid of the error by adding the : any
to the formats
object, though I think this is not the best solution?
interface Props {
keyword: string;
hex: string;
rgb: string;
copyFormat: string;
}
export default ({ keyword, hex, rgb, copyFormat }: Props) => {
const formats: any = {
keyword,
hex: hex.toUpperCase(),
rgb: `rgb(${rgb})`,
};
return <p>{formats[copyFormat]}</p>;
};