TypeScript type for reduce

You can do it like this using Record and keyof:

export default Object.keys(size).reduce((acc, cur) => {
  acc[cur] = `(min-width: ${size[cur]}px)`;

  return acc;
}, {} as Record<keyof MediaQueryProps, string>);

If you want the accumulator value to be indexable by string, Record<string, string> should do the trick. You can pass this as the type argument to reduce

interface MediaQueryProps {
  [key: string]: number;
}

const size: MediaQueryProps = {
  small: 576,
  medium: 768,
  large: 992,
  extra: 1200
};

export default Object.keys(size).reduce<Record<string, string>>((acc, cur) => {
  acc[cur] = `(min-width: ${size[cur]}px)`;
  return acc;
}, {});

Playground link


With TypeScript 4.1 you can also take advantage of Template Literal Types with as type casting. TypeScript Playground Link.

// .ts
interface MediaQueryProps {
  [key: string]: number;
}

const size = {
  small: 576,
  medium: 768,
  large: 992,
  extra: 1200
} as const;

const mediaQueryKeys = Object.keys(size) as Array<keyof typeof size>;

const mediaQueries = mediaQueryKeys.reduce((acc, cur) => {
  acc[cur] = `(min-width: ${size[cur]}px)`;

  return acc;
}, {} as Record<`${keyof typeof size}`, string>);

export default mediaQueries;

// d.ts
declare const mediaQueries: Record<"small" | "medium" | "large" | "extra", string>;
export default mediaQueries;

Tags:

Typescript