8

I am trying to utilize react-select and have the following code:

import React, {useState} from 'react';
import LanguageChange from '../../../Icons/LanguageChange';
import Select, { ValueType } from 'react-select';

type OptionType = {
    value: string;
    label: string;
  };


export const LanguageSelector = () => {
    const languageOptions: OptionType[] = [
        { value: 'English', label: 'EN' },
        { value: 'German', label: 'DE' },
        { value: 'French', label: 'FR' },
      ];
    const [selectedOption, setSelectedOption] = useState<ValueType<OptionType>>(languageOptions[0]);
    const handleChange = (option: ValueType<OptionType>) => {
    setSelectedOption(option);
  };

    return (
        <LanguageChange>
            <Select
                value={selectedOption}
                onChange={setSelectedOption}
                options={languageOptions}
            />
        </LanguageChange>
    )
}

But I keep getting the following error: (alias) type ValueType<OptionType extends OptionTypeBase, IsMulti extends boolean> = IsMulti extends true ? OptionsType : OptionType | null import ValueType Generic type 'ValueType' requires 2 type argument(s).ts(2314)

Any idea what I'm missing here?

2 Answers 2

14

ValueType requires two generics: the OptionType which you have provided and IsMulti which is either true or false. IsMulti determines whether or not it is an array. If you have an OptionType with {value: string}, the ValueType if it's a multiple select should be string[] whereas for a single select it would be string.

In your case you have a single select so you can use ValueType<OptionType, false>. But you can also just use string because you already know that the value type of your options is string so there is no need to work backwards.

Source Code

Sign up to request clarification or add additional context in comments.

2 Comments

@sbuck89 please dont forget to accept the answer
Is it possible to explain more export type ValueType<OptionType extends OptionTypeBase, IsMulti extends boolean> = IsMulti extends true ? OptionsType<OptionType> : OptionType | null; why = IsMulti extends true .. its good practice to learn more about TypeScript @linda
0

Update your onChange function to accept params like this:

onChange: (value: ValueType<OptionType, IsMulti>, actionMeta: ActionMeta<OptionType>) => void;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.