Description:
In TypeScript projects, the onValueChange function of the SegmentedButtons component currently returns a generic string. This creates challenges when assigning the value to a variable that has a specific union type (e.g., Nutrient = 'protein' | 'fat' | 'carbs'). Developers are forced to implement additional validation and type casting, which can lead to less clean code and potential runtime errors.
Steps to reproduce:
Define a union type for valid button values.
Use the SegmentedButtons component and attempt to directly assign the onValueChange value to the typed variable.
TypeScript will raise an error due to the mismatch in types.
Example Code:
type Nutrient = 'protein' | 'fat' | 'carbs';
// State variable for the selected nutrient
const [nutrient, setNutrient] = useState<Nutrient>('protein');
<SegmentedButtons
value={nutrient}
onValueChange={(value) => {
setNutrient(value); // TypeScript expects `value` to be Nutrient here
}}
buttons={[
{ value: 'protein', label: 'Protein' },
{ value: 'fat', label: 'Fats' },
{ value: 'carbs', label: 'Carbs' },
]}
/>
The Issue:
The problem arises in the onValueChange callback. Since the value parameter is inferred as a string, TypeScript cannot guarantee that it is one of the valid Nutrient values. Thus, if you try to assign value directly to nutrient, TypeScript will raise a type error:
Error
Type 'string' is not assignable to type 'Nutrient'.
Environment:
"react-native-paper": "^5.12.5",
**Willingness to Contribute:**
I am willing to contribute to solving this issue if assigned under Hacktoberfest. I look forward to helping enhance the library for better TypeScript support.
"typescript": "5.0.4"
Description: In TypeScript projects, the onValueChange function of the SegmentedButtons component currently returns a generic string. This creates challenges when assigning the value to a variable that has a specific union type (e.g., Nutrient = 'protein' | 'fat' | 'carbs'). Developers are forced to implement additional validation and type casting, which can lead to less clean code and potential runtime errors.
Steps to reproduce: Define a union type for valid button values. Use the SegmentedButtons component and attempt to directly assign the onValueChange value to the typed variable. TypeScript will raise an error due to the mismatch in types.
Example Code:
The Issue: The problem arises in the onValueChange callback. Since the value parameter is inferred as a string, TypeScript cannot guarantee that it is one of the valid Nutrient values. Thus, if you try to assign value directly to nutrient, TypeScript will raise a type error:
Error Type 'string' is not assignable to type 'Nutrient'.
Environment: