Skip to content

Instantly share code, notes, and snippets.

@mattpocock
Last active May 21, 2019 08:47
Show Gist options
  • Select an option

  • Save mattpocock/92068df5d977ad9b3611c8bd5fb73b50 to your computer and use it in GitHub Desktop.

Select an option

Save mattpocock/92068df5d977ad9b3611c8bd5fb73b50 to your computer and use it in GitHub Desktop.
Function for creating theme functions out of a theme file for styled components
import optionalChain from 'utils/helperFunctions/optionalChain';
const recursivelyCreateThemeFunctions = (
themeObject: ThemeObject,
steps: (string | number)[] = [],
): ThemeFunction | ThemeObjectReturn => {
if (Array.isArray(themeObject)) {
// @ts-ignore
return themeObject.map((value, index) =>
recursivelyCreateThemeFunctions(value, [...steps, index]),
);
}
if (typeof themeObject === 'object' && themeObject !== null) {
return {
...Object.keys(themeObject)
.map(key => ({
[key]: recursivelyCreateThemeFunctions(themeObject[key], [
...steps,
key,
]),
}))
.reduce((a, b) => ({ ...a, ...b }), {}),
};
}
return ({ theme }) => optionalChain(theme, ...steps);
};
type ThemeObject = { [index: string]: ThemeObject } | string | number | any[];
type ThemeObjectReturn =
| { [index: string]: ThemeFunction | ThemeObjectReturn }
| ({ [index: string]: ThemeFunction | ThemeObjectReturn } | ThemeFunction)[];
type ThemeFunction = (param: { theme: any }) => any;
const createThemeFunctions = <Theme>(
themeObject: ThemeObject,
): { [K in keyof Theme]: ThemeFunction } => {
// @ts-ignore
return recursivelyCreateThemeFunctions(themeObject);
};
export default createThemeFunctions;
import { variables } from 'cssSettings';
import createThemeFunctions from 'createThemeFunctions';
const theme = createThemeFunctions<typeof variables>(variables);
export default theme;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment