Home > front end >  Typescript: how to make addiction from one field to another?
Typescript: how to make addiction from one field to another?

Time:02-01

So, I have interface for select. I need have type for value. If multiple is equal true, value type must be string[] or string if multiple disabled.

interface SelectProps {
  multiple?: boolean;
  value: string | string[];
}

Component:

const Select = (props: SelectProps) => {
   // code
};

I tried to use generic, like this

interface SelectProps<Multiple extends boolean | undefined> {
  multiple?: boolean;
  value: Multiple extends true ? string[] : string;
}


const Select = (props: SelectProps<typeof props.multiple>) => {
   // code
};

but I recieve error: 'multiple' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

CodePudding user response:

Select should also be a generic and it should forward type parameter to SelectProps Also, multiple should be of type Multiple

playground

  • Related