A
A
Anastasia2022-02-22 13:49:14
typescript
Anastasia, 2022-02-22 13:49:14

What is the reason for the ts error when passing props to a component?

When trying to pass all other props - { ...props } - props Options to the Select component, it starts highlighting with an error:

Type 'OptionType[]' is not assignable to type 'readonly (string | number | GroupBase)[]'.
Type 'OptionType' is not assignable to type 'string | number | GroupBase'.
Property 'options' is missing in type 'OptionType' but required in type 'GroupBase'.

if I don't try to spread props in Select, then everything is OK, options is passed without errors. Perhaps I am incorrectly extending the ISelectProp interface from a naive select element? And how to pass ref to the Select component with such a record?

import React from 'react';
import Select from 'react-select';

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

interface ISelectProps extends React.ComponentPropsWithRef<'select'> {
    caption?: string;
    options?: OptionType[];
    className?: string;
}

export const DefaultSelect = React.forwardRef<HTMLSelectElement, ISelectProps>(
    ({
         options = [], 
         placeholder = 'Выберите марку',
         disabled, 
         ...props
     }, ref
    ) => {

        return (
            <Select
                options={options}
                placeholder={placeholder}
                isDisabled={disabled}
                noOptionsMessage={() => 'Нет совпадений'}
                {...props}
            />
        );
    },
);

DefaultSelect.displayName = 'Select';

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2022-02-22
@KnopkaNen

Somewhere in the >260 properties from React.ComponentPropsWithRef<'select'>is a property that the generic Optionin Selectsets as string | numberhaving a higher priority than what you actually put in Options. You can search by yourself removing one by one or comparing with the declaration for Select.
But in principle, just throw out the solution React.ComponentPropsWithRef<'select'>, because. you're extending not native select, but react-select.

import Select, { Props } from 'react-select';

interface ISelectProps extends Props<OptionType> {
    caption?: string;
    disabled?: boolean
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question