Currently, I'm developing a component library and facing an issue with a TypeScript error:
An Element implicitly has an 'any' type due to the expression of type 'levelTypes | semanticTypes' being unable to index type '{ level1: { highEmphasis: string; mediumEmphasis: string; outlineHighEmphasis: string; outlineMediumEmphasis: string; semantic: { info: string; onInfo: string; negative: string; onNegative: string; ... 12 more ...; AIGradientEndpoint: string; }; interactive: { ...; }; }; ... 15 more ...; aiIntense: { ...; }; } | { ....'.
Property 'level1' is not found in type '{ level1: { highEmphasis: string; mediumEmphasis: string; outlineHighEmphasis: string; outlineMediumEmphasis: string;'ts(7053)
The part that's causing trouble is when trying to dynamically access two different keys in my color palette object:
theme.fdsTheme.palette[getForeground(level)][level].interactive.highEmphasisSurface
Including my component code for reference:
import styled from "@emotion/styled";
// Rest of the code...
:)
I have been searching for solutions related to accessing two keys dynamically but have only come across examples dealing with single key accesses. Here is what I attempted:
// Define my theme as a separate type
import "@emotion/react";
import { Theme } from "../theme";
type DefaultTheme = typeof Theme;
declare module "@emotion/react" {
export interface Theme extends DefaultTheme {}
}
import { Theme } from "@emotion/react";
// Previous Code...
const StyledButton = styled(BaseButton)<ButtonStyleProps>(({ theme, level }) => {
return {
[`&.${buttonClasses.root}`]: {
// various styles...
"&.fds-Button-primary": {
backgroundColor:
theme.fdsTheme.palette[getForeground(level) as keyof Theme][level as keyof Theme].interactive.highEmphasisSurface,
},
},
};
});
UPDATE:
To simplify things, here's some dummy code:
interface TestProps {
levelOne: "color" | "typo";
levelTwo: "level1" | "level2" | "level3";
}
function TestComponent({ levelOne, levelTwo }: TestProps) {
const theme = {
color: {
level1: {
color: "",
},
level2: {
color: "",
},
},
typo: {
level1: {
color: "",
},
level2: {
color: "",
},
level3: {
color: "",
},
},
};
const checkLevel = (
level: "level1" | "level2" | "level3"
): "color" | "typo" => {
return level === "level1" || level === "level2" ? "color" : "typo";
};
const c = theme[checkLevel(levelTwo)][levelTwo].color;
console.log(c);
}
The problematic line would be:
theme[checkLevel(levelTwo)][levelTwo].color;