mui / material-ui

Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
https://mui.com/material-ui/
MIT License
93.89k stars 32.26k forks source link

[Slider] Allow generic value type to narrow onChange value type #37854

Open eloiqs opened 1 year ago

eloiqs commented 1 year ago

Duplicates

Latest version

Summary 💡

Giving a number type as value should narrow onChange value param to number, and giving a number[] type as value should narrow onChange value param to number[]

Examples 🌈

<Slider value={1} onChange={(e, value:number) => {}} /> <Slider value={[1,2]} onChange={(e, value:number[]) => {}} />

Motivation 🔦

We currently have to do something like this <Slider value={1} onChange{(e, value) => typeof value === 'number' ? ... : ...what do i do here? throw an error? } /> to make typescript happy

DiegoAndai commented 1 year ago

Hey @eloiqs, thanks for the report!

A workaround would be using a Type Assertion, for example:

function SliderExample() {
  const [value, setValue] = React.useState(20);

  const handleChange = (event, newValue) => {
    setValue(newValue as number); // or number[] for a range slider
  };

  return (
    <Box sx={{ width: 300 }}>
      <Slider value={value} onChange={handleChange} />
    </Box>
  );
}

Using the as keyword, you manually assure Typescript that newValue is a number, of which you can be sure as the provided value is a number as well.

Implementing a generic to narrow down the callback would be nice though. If you (or anyone) would like to work on a PR, that would be great as well 😊🚀

gitstart commented 1 year ago

@DiegoAndai @eloiqs I would like to pick this up

DiegoAndai commented 1 year ago

@gitstart sure! let me know if you need any help