0

I have this Select component:

type SelectProps = {
  title: string;
  name: string;
  items: string[];
  onChange: (e: ChangeEvent<HTMLSelectElement>) => void;
  defValue: string;
};

const Select: FC<SelectProps> = ({ title, name, items, onChange, defValue }) => {
  return (
    <>
      <label htmlFor={name}>
        {title}:
      </label>
      <select name={name} onChange={onChange} defaultValue={defValue}>
        {items.map((item) => (
          <option value={item} key={item}>
            {item}
          </option>
        ))}
      </select>
    </>
  );
};

and I'm handling onChange with this function:

const onThemeChange = (e: ChangeEvent<HTMLSelectElement>) => {
  const theme = e.target.value;
  setTheme(theme)
};

...

<Select
  title='Theme'
  defValue={props.theme}
  name='theme'
  items={['light', 'dark']}
  onChange={onThemeChange}
/>

My setTheme action creator accepts argument with type 'light' | 'dark', so I'm getting an error:

Argument of type 'string' is not assignable to parameter of type '"light" | "dark"'

What is the best way to solve this issue?

5
  • You can suggest typescript const theme = e.target.value as "light" | "dark"; Jun 5, 2020 at 11:39
  • 1
    How is theme state defined on your component?
    – wentjun
    Jun 5, 2020 at 11:39
  • I'm passing it from redux Jun 5, 2020 at 11:43
  • So setTheme is an action dispatch from the redux store?
    – wentjun
    Jun 5, 2020 at 11:45
  • yes export const setTheme = (theme: 'light' | 'dark'): ActionTypes => { return { type: SET_THEME, theme, }; }; Jun 5, 2020 at 11:47

2 Answers 2

1

There is away, but it requires a little trick.

First, let's recognize the relationships between types in your SelectProps:

  • the items are string literals
  • in onChange, the event will have a target.value equal to one of your items
  • the defValue should also be one of the items

To express these constraints, we need to use a generic interface.

type SelectProps<T extends string> = {
  title: string;
  name: string;
  items: T[];
  onChange: (e: ChangeEvent<HTMLSelectElement> & { target: { value: T }}) => void;
  defValue: DeferTypeInference<T>;
};

const Select = function<T extends string>({ title, name, items, onChange, defValue }: SelectProps<T>) {
  return (
    <>
      <label htmlFor={name}>
        {title}:
      </label>
      <select name={name} onChange={onChange} defaultValue={defValue}>
        {items.map((item) => (
          <option value={item} key={item}>
            {item}
          </option>
        ))}
      </select>
    </>
  );
};

We have achieved everything.

<Select
  title='Theme'
  defValue="light" // only "light" or "dark" are accepted
  name='theme'
  items={['light', 'dark']}
  onChange={event => event.target.value} // event.target.value is "light" or "dark"
/>

Note the use of a type called DeferTypeInference<T>. If you're curious why it's there, check out this answer.

0

The quickest way of doing so would be to do type assertions.

Assuming that this is how you initialised the state,

type ThemeState = 'light' | 'dark';

const [theme, useTheme] = useState<ThemeState>('light');

And then, on your onThemeChange method, you will assert the value as ThemeState

const theme = e.target.value as ThemeState;
2
  • I know about this method, but seem like a workaround to me. Is this the proper way? Jun 5, 2020 at 12:00
  • @РичардФейнман Not that I know of. But I would recommend you to make the items under` SelectProps` to be more type-safe, such that it will not accept any random strings. You can consider changing it to this, items: ThemeState[];
    – wentjun
    Jun 5, 2020 at 12:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.