How to get autocomplete for object keys in TypeScript

Viewed 911

I currently have this type

export type Styles = Record<string, Style>

I use it like this

// Button.styles.ts
const styles: Styles = {
  primary: ({ colors }) => ({
    backgroundColor: colors.primary,
  }),
  secondary: ({ colors }) => ({
    backgroundColor: colors.secondary,
  }),
}

But when I import it in another file I don't get autocomplete

import styles from './Button.styles.ts'

// styles.
// I get nothing if I start typing this, but I want to see a list of "primary, secondary"

basically, I want to infer the keys of this so I get autocomplete when the object is used

2 Answers

I think that it is redundant to annotate the type. You can remove the Styles type, it will be inferred.

If you still want to annotate, the type should be:

// Button.styles.ts

type StyleParams = {
  colors: {
    primary: string,
  },
  secondary: string,
};

type Styles = {
  primary(params: StyleParams): string,
  secondary(params: StyleParams): string,
};

const styles: Styles = {
  primary: ({ colors }) => ({
    backgroundColor: colors.primary,
  }),
  secondary: ({ colors }) => ({
    backgroundColor: colors.secondary,
  }),
};

Another way (although it's not using an object per se:

export function primary({ colors }) => { ... }
export function secondary({ colors }) => { ... }
export const something = {};

Then, in another file you can import them all:

import * as everything from "./Button.styles";

everything.secondary({ colors });

Now: everything. should suggest autocomplete by each of those exported properties (primary, secondary, something, etc.)

Related