New to Typescript here. I have a Material UI Slider
that I'd like to set my age
state variable with, but I'm getting a Typescript error due to the typing of age
being number
and onChange
value being number | number[]
. How can I tell onChange
to always expect a number
?
code:
<Slider
defaultValue={25}
step={1}
min={0}
max={100}
valueLabelDisplay="auto"
onChange={handleAgeSliderChange}
/>
onChange: (use Redux store)
const handleAgeSliderChange = (event:any, newValue: number | number[]) =>{
const new_inputs = { ...props.userInput, age: newValue}
props.updateUserInputs(new_inputs)
}
and the error:
Types of property 'age' are incompatible.
Type 'number | number[]' is not assignable to type 'number'.
Type 'number[]' is not assignable to type 'number'.
EDIT: Some more details:
in ActionCreators.tsx
export const updateUserInputs = (input: UserInputs) : ActionTypes.UserInputActions => ({
type: ActionTypes.UPDATE_USER_INPUTS,
payload: input
})
in userinputs.tsx
const initialState: UserInputs = {
age: 25,
ethnicity: "white",
country: "US",
smoking: false
}
export const userInputReducer = (
state = initialState,
action: ActionTypes.UserInputActions
) => {
switch (action.type) {
case ActionTypes.UPDATE_USER_INPUTS:
const new_input = action.payload
return {...state, userInput: new_input}
default:
return {...state}
}
};
in types.tsx
export interface UserInputs {
age: number;
ethnicity: string;
country: string;
smoking: boolean;
}