Home > database >  react typescript type based on other type
react typescript type based on other type

Time:10-18

I have a component like this

type inputProps = {
  value: string | number | boolean
  onChange: (arg: string | number | boolean) => void
}

const Input = ({value, onChange}: inputProps) => {
  return <div />
}

const OtherComponent = () => {
  const [value, setValue] = React.useState(5)

  // onChange type not compatible
  return <Input  value={value} onChange={setValue} />
}

const AnotherComponent = () => {
  const [value, setValue] = React.useState('Hey')

  // onChange type not compatible
  return <Input  value={value} onChange={setValue} />
}

playground link

Is it possible to make the arg of the onChange function dependent on the value?

CodePudding user response:

Yes. It is possible using Generics:

type inputProps<T> = {
  value: T;
  onChange: (arg: T) => void;
};

const Input = <T,>({ value, onChange }: inputProps<T>) => {
  return <div />;
};

CodePudding user response:

You can first define the InputProps as generic.

type InputProps<T extends string | number | boolean> = {
  value: T;
  onChange: (arg: T) => void;
};

Then you can use type union for different types.

const Input = ({
  value,
  onChange,
}: InputProps<string> | InputProps<number> | InputProps<boolean>) => {
  return <div />;
};

const OtherComponent = () => {
  const [value, setValue] = React.useState(5);

  return <Input value={value} onChange={setValue} />;
};

const AnotherComponent = () => {
  const [value, setValue] = React.useState('Hey');

  return <Input value={value} onChange={setValue} />;
};
  • Related