Home > Net >  How to associate two props parameters types together in Typescript
How to associate two props parameters types together in Typescript

Time:02-21

I am creating a component that will be used in two different components. In the component A the main param will be typed as typeA and the callback will have a typeA param and in the other component B the main param will be typed as typeB and the callback will have a typeB param. I am getting an error in the new component1 because the callback can't get variable of typeA | typeB (which makes sense).

Here is a simple version of how it looks:

type Props = {
  option: typeA | typeB;
  callback: (e, a: typeA) => void | (e, b: typeB) => void:
}
export const Component1 : (props: Props) => {
  return (
    <Button onClick={() => {props.callback(props.option)}> 
      {props.option.label} 
    </Button>

}

Is there a way to associate types together in the props in order to say that the callback from component B will only be associated to a param of typeB?

CodePudding user response:

I think what you need is called Generics in Typesciript. You basically pass a Type parameter (variable T) into the Props Type, in the place where you define your specific component.

type typeA = {
  label: string
}

type typeB = {
  label: number
}

type Props<T> = {
  option: T;
  callback: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>, a: T) => void | ((e: React.MouseEvent<HTMLButtonElement, MouseEvent>, b: T) => void);
}
export const Component1 = (props: Props<typeA>) => {
  return (
    <button onClick={(e) => {props.callback(e, props.option)}}> 
      {props.option.label} 
    </button>
  )
}

export const Component2 = (props: Props<typeB>) => {
  return (
    <button onClick={(e) => {props.callback(e, props.option)}}> 
      {props.option.label} 
    </button>
  )
}

CodePudding user response:

type Props<T> = {
  option: T;
  callback: (e, a: T) => void
}
export const Component1 : (props: Props<Type1>|Props<Type2>) => {
  return (
    <Button onClick={() => {props.callback(props.option)}> 
      {props.option.label} 
    </Button>

}

  • Related