TS: Declare object as a type while keeping the keys

Viewed 37

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?

0 Answers
Related