Skip to content
This repository has been archived by the owner on Jan 16, 2022. It is now read-only.

Commit

Permalink
fix: better type inference for MediaQuery (#180)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmkn authored and juanpicado committed Oct 13, 2019
1 parent d1b3e6e commit e0e7c07
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions src/utils/styles/media.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { css } from 'emotion';
import { css, Interpolation } from 'emotion';

export const breakpoints = {
small: 576,
Expand All @@ -8,26 +8,31 @@ export const breakpoints = {
xlarge: 1275,
};

type Sizes = keyof typeof breakpoints;
type Breakpoints = typeof breakpoints;
type Sizes = keyof Breakpoints;

type MediaQuery = {
[key in Sizes]: (cls: any) => string;
type MediaQuery<T> = {
[P in keyof T]: (args: Interpolation, key?: P) => string;
};

const mq: MediaQuery = Object.keys(breakpoints).reduce(
(accumulator, label) => {
const prefix = typeof breakpoints[label] === 'string' ? '' : 'min-width:';
const suffix = typeof breakpoints[label] === 'string' ? '' : 'px';
accumulator[label] = cls =>
css`
@media (${prefix + breakpoints[label] + suffix}) {
${cls};
}
`;
return accumulator;
},
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
{} as MediaQuery
);
function constructMQ(breakpoint: Sizes, args: Interpolation): string {
const label = breakpoints[breakpoint];
const prefix = typeof label === 'string' ? '' : 'min-width:';
const suffix = typeof label === 'string' ? '' : 'px';

return css`
@media (${prefix + breakpoints[breakpoint] + suffix}) {
${args};
}
`;
}

const mq: MediaQuery<Breakpoints> = {
small: (args, b = 'small') => constructMQ(b, args),
large: (args, b = 'large') => constructMQ(b, args),
container: (args, b = 'container') => constructMQ(b, args),
medium: (args, b = 'medium') => constructMQ(b, args),
xlarge: (args, b = 'xlarge') => constructMQ(b, args),
};

export default mq;

0 comments on commit e0e7c07

Please sign in to comment.