TypeScript: Unions can't be used in index signatures

April 02, 2020

unions can't be used in index signatures, use a mapped object type instead

I must trigger this error in TypeScript at least twice a day, and I’m sick of looking up and reading through the Github issue that gives you the fix. Too much cognitive overhead when all I want to do is copy and paste the solution.

Here’s how to fix it. Instead of trying to use a union type directly as an index signature (like this):

type ButtonVariant = 'normal' | 'ghost';
const ButtonVariants: {
  [variantName: ButtonVariant]: SxStyleProp;
}

Use the in keyword instead:

type ButtonVariant = 'normal' | 'ghost';
const ButtonVariants: {
  [variantName in ButtonVariant]: SxStyleProp;
}

That’s all. Now I can look at this post instead of Googling next time.

Elliot