I'm trying to add TypeScript types to the following code:
const [selectedDevice, setSelectedDevice] = useState<DesktopOrMobile>(DesktopOrMobile.desktop);
const handleChange = (event: React.ChangeEvent<{ value: DesktopOrMobile }>): void => {
setSelectedDevice(event.target.value);
};
<select value={selectedDevice} onChange={handleChange}>
<option value={DesktopOrMobile.desktop}>Desktop</option>
<option value={DesktopOrMobile.mobile}>Mobile</option>
</select>
But I get this error:
TS2322: Type '(event: React.ChangeEvent<{ value: DesktopOrMobile;}>) => void' is not assignable to type '(event: ChangeEvent) => void'. Types of parameters 'event' and 'event' are incompatible. Type 'ChangeEvent' is not assignable to type 'ChangeEvent<{ value: DesktopOrMobile; }>'. Type 'HTMLSelectElement' is not assignable to type '{ value: DesktopOrMobile; }'. Types of property 'value' are incompatible. Type 'string' is not assignable to type 'DesktopOrMobile'.
I know that the problem is that event.target.value from the onChange event on the select list has a type of string not DesktopOrMobile but I'm not sure what the best solution is.
UPDATE: I could use an enum but not sure if there's a better way than type casting:
import * as React from "react";
import {useState} from 'react'
enum DesktopOrMobile {
mobile = 'mobile',
desktop = 'desktop'
}
export default function App() {
const [selectedDevice, setSelectedDevice] = useState<DesktopOrMobile>(DesktopOrMobile.mobile);
const handleChange = (value: DesktopOrMobile): void => {
setSelectedDevice(value);
};
return (
<div>
<select value={selectedDevice} onChange={e => handleChange(e.target.value as DesktopOrMobile)}>
<option value={DesktopOrMobile.desktop}>Desktop</option>
<option value={DesktopOrMobile.mobile}>Mobile</option>
</select>
</div>
);
}