I have problems with dynamisation in Typescript. I know that TS works statically. However, there are sometimes situations where I want to access an object dynamically and cannot do this directly via any generics because the values are generated. Perhaps you could help me to understand the whole thing a little better. I have the following example:
<code>import React from "react";
const FontTheme = {
headline: {
small: 12,
medium: 16,
large: 20,
},
label: {
tiny: 4,
small: 12,
},
button: {
small: 12,
},
} as const;
interface TextComponentProps {
variant:
| "headline-small"
| "headline-medium"
| "headline-large"
| "label-tiny"
| "label-small"
| "button-small";
}
function TextComponent({ variant }: TextComponentProps) {
const [element, size] = variant.split("-");
const styles = {
...FontTheme[element][size],
};
console.log(styles);
return <h1>Text</h1>;
}
export { TextComponent };
</code>
<code>import React from "react";
const FontTheme = {
headline: {
small: 12,
medium: 16,
large: 20,
},
label: {
tiny: 4,
small: 12,
},
button: {
small: 12,
},
} as const;
interface TextComponentProps {
variant:
| "headline-small"
| "headline-medium"
| "headline-large"
| "label-tiny"
| "label-small"
| "button-small";
}
function TextComponent({ variant }: TextComponentProps) {
const [element, size] = variant.split("-");
const styles = {
...FontTheme[element][size],
};
console.log(styles);
return <h1>Text</h1>;
}
export { TextComponent };
</code>
import React from "react";
const FontTheme = {
headline: {
small: 12,
medium: 16,
large: 20,
},
label: {
tiny: 4,
small: 12,
},
button: {
small: 12,
},
} as const;
interface TextComponentProps {
variant:
| "headline-small"
| "headline-medium"
| "headline-large"
| "label-tiny"
| "label-small"
| "button-small";
}
function TextComponent({ variant }: TextComponentProps) {
const [element, size] = variant.split("-");
const styles = {
...FontTheme[element][size],
};
console.log(styles);
return <h1>Text</h1>;
}
export { TextComponent };
Even if I use generics, I could not solve the problem, as the values would be generated by the split method. Is there another way to solve the problem without casting the values? or is it possible to use generics after all?