3

I would like to type our Material UI styles and classes. For that I have the following construction:

import { StyleRulesCallback, StyleRules } from "@material-ui/core/styles";

export type StyleType = StyleRulesCallback<string> | StyleRules<string>;

export type ClassesType<S extends StyleType> =
  S extends StyleRulesCallback<string>
    ? { [K in keyof ReturnType<S>]: string }
    : { [K in keyof S]: string };

Now, when I have some styles like

const styles: StyleType = {
  root: {
    flexGrow: 1
  }
};

and I type them as StyleType and the classes as ClassesType<typeof styles>, the inferred type of classes is {[x: string]: string}. However, I would like to keep the keys, i.e. that classes is of type {root: string} which works when I remove the typing of the styles.

Is there a way of typing the styles as StyleType (or similar) while still keeping the keys?

Richard
  • 514
  • 3
  • 9
  • 1
    I don't have typing from @material-ui in scope so I can't demo this directly. Taking the answer from the other question and adapting yields something like [this code](https://tsplay.dev/wRRzXw), but it would be nice if you could give a standalone [mre] to be sure. Good luck! – jcalz Apr 12 '22 at 17:30
  • Hey @jcalz That exactly solves my problem! Thank you :) – Richard Apr 13 '22 at 07:31

0 Answers0