[Typescript] Wrap an function with Identity function to provide clean Type API

For the following code:

import { CSSProperties } from 'react';

const useStyled = <TTheme = {}>(func: (theme: TTheme) => CSSProperties) => {
  return {} as CSSProperties;
};

interface MyTheme {
  color: {
    primary: string;
  };
  fontSize: {
    small: string;
  };
}

const buttonStyle = useStyled<MyTheme>((theme) => ({
  color: theme.color.primary,
  fontSize: theme.fontSize.small,
}));

const divStyle = useStyled<MyTheme>((theme) => ({
  backgroundColor: theme.color.primary,
}));

 

Everytime, we need to do useStyled<MyTheme>, we can use identity to wrap `useStyled` to reduce duplication:

import { CSSProperties } from 'react';

const makeUseStyled = <TTheme = {}>() => {
  return (func: (theme: TTheme) => CSSProperties) => {
    return {} as CSSProperties;
  };
};

const useStyled = makeUseStyled<MyTheme>();

interface MyTheme {
  color: {
    primary: string;
  };
  fontSize: {
    small: string;
  };
}

const buttonStyle = useStyled((theme) => ({
  color: theme.color.primary,
  fontSize: theme.fontSize.small,
}));

const divStyle = useStyled((theme) => ({
  backgroundColor: theme.color.primary,
}));

 

posted @ 2023-02-25 20:45  Zhentiw  阅读(12)  评论(0编辑  收藏  举报