反应 select 样式和打字稿

react select styles and typescript

根据 react-select docs,我可以像这样访问传递到 Select 正文中的我自己的参数:

const customStyles = {
  menu: (provided, state) => ({
    ...provided,
    width: state.selectProps.width,
    borderBottom: '1px dotted pink',
    color: state.selectProps.menuColor,
    padding: 20,
  }),

  control: (_, { selectProps: { width }}) => ({
    width: width
  }),

  singleValue: (provided, state) => {
    const opacity = state.isDisabled ? 0.5 : 1;
    const transition = 'opacity 300ms';

    return { ...provided, opacity, transition };
  }
}

但是如果我在打字稿中有这样的东西

const customStyles: SelectProps["styles"] = {
  valueContainer: (provided, { selectProps: { size } }) => {
    const px = {
      sm: "0.75rem",
      md: "1rem",
      lg: "1rem"
    };

    return {
      ...provided,
      padding: `0.125rem ${px[size]}` 
    };
  },

};

${px[size]} 部分抛出错误

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ sm: string; md: string; lg: string; }'.

说明传入的size是一个any类型,typescript不知道是不是smmdlg的key之一.

方式01:使用cast通知打字稿,大小是smmdlg[=之一22=]

const px = {
  sm: "0.75rem",
  md: "1rem",
  lg: "1rem"
};

px[size as 'sm' | 'md' | 'lg']

方式 02:为 px 设置一个类型并使用它的键进行转换

type PxType = { [k in 'sm' | 'md' | 'lg']: string }

const px: PxType = {
  sm: "0.75rem",
  md: "1rem",
  lg: "1rem"
};

px[size as keyof PxType]