首页 > 其他分享 >[Typescript] Wrap an function with Identity function to provide clean Type API

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

时间:2023-02-25 20:57:37浏览次数:31  
标签:function Typescript const provide primary color theme fontSize useStyled

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,
}));

 

标签:function,Typescript,const,provide,primary,color,theme,fontSize,useStyled
From: https://www.cnblogs.com/Answer1215/p/17155339.html

相关文章