Interface definition for typescript method parameter problem?

33 Views Asked by At

A method is defined with ts. According to the conditions, the order of parameters in the callback method is a, b, or b, a.

if (props.xxx) {
    props.onChange(a, b)
} else {
    props.onChange(b, a)
}

How should this onChange method be described in the interface?

1

There are 1 best solutions below

0
Kan Robert On
type OnChange = {
    (a: string, b: number): void;
    (a: number, b: string): void;
};

type IProps = {
    xxx: boolean;
    onChange: OnChange;
};

Instead of using function overloading, use union types:

interface FooParams {
    xxx: true;
    onChange: (a: string; b: number) => void;
}
interface BarParams {
    xxx: false;
    onChange: (a: number; b: string) => void;
}
type IProps2 = FooParams | BarParams

const App = (props: IProps2) => {
  if (props.xxx) {
    props.onChange('', 1)
  }
}