Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ant design multiple select does not accept array as default value

Title says what is the problem, I have a compilation error where TS says : Type string[] is not assignable to type 'string | number' But the documentation says I can do This :

                <Select
                    mode="multiple"
                    defaultValue={['ALL']}
                    onChange={this.handleChange}
                >
                    <Option value="ALL">Tout</Option>
                    {mediaGenres.map((mg: MediaGenre) => <Option key={mg.id} value={mg.id}>{mg.label}</Option>)}
                </Select>

When I check the type file for the select It is as this :

export declare type SelectValue = string | string[] | number | number[] | LabeledValue | LabeledValue[];
export interface SelectProps<T = SelectValue> extends AbstractSelectProps {
    value?: T;
    defaultValue?: T;

So it must be accepted as string[]

I checked two versions of antd

What do I miss ?

like image 535
C Taque Avatar asked Apr 24 '26 15:04

C Taque


2 Answers

I created a sandbox and I get no type error.

Try this snippet out.

export default function App() {
  const { Option } = Select;
  return (
    <div className="App">
      <Select
        mode="multiple"
        defaultValue={["1", "2"]}
        onChange={(e: string[] | number[] | undefined) => {
          console.log(e);
        }}
      >
        <Option value="1">1</Option>
        <Option value="2">2</Option>
        <Option value="3">3</Option>
        <Option value="4">4</Option>
      </Select>
    </div>
  );
}

If it does not works, you can compare your tsconfig.json with the config of this example: https://codesandbox.io/s/awesome-solomon-kinkc

like image 78
Peter Ambruzs Avatar answered Apr 26 '26 06:04

Peter Ambruzs


what happens if you assign your default value as a variable instead of creating it on the fly?

let defaultSelections = ["ALL"];
...
...
<Select
  mode="multiple"
  defaultValue={defaultSelections}
  onChange={this.handleChange}
>
  <Option value="ALL">Tout</Option>
  {mediaGenres.map((mg: MediaGenre) => <Option key={mg.id} value={mg.id}>{mg.label}</Option>)}
</Select>
like image 23
Martyn Compton Avatar answered Apr 26 '26 06:04

Martyn Compton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!