0

According to the react-select docs I can gain access to my own arguments passed into the Select body like this:

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

However if I have something like this in typescript

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

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

};

The ${px[size]} part throws an error

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

1 Answer 1

1

It indicates the incoming size is an any type and typescript does not know if it is one of the keys of sm md lg.

Way 01: use cast to inform typescript, size is one of the sm md lg

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

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

Way 02: Have a type for px and use its key for casting

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

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

px[size as keyof PxType]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.