接口定义的typescript方法参数问题?



方法用ts定义。根据条件,回调方法中参数的顺序为:abba

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

如何在接口中描述这个onChange方法?

type OnChange = {
(a: string, b: number): void;
(a: number, b: string): void;
};
type IProps = {
xxx: boolean;
onChange: OnChange;
};

不使用函数重载,使用联合类型:

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)
}
}

最新更新