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

用ts定义了一个方法,根据条件,回调方法中参数顺序是a, b,也可能是b, a。

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

这个onChange方法在interface里该怎么描述呢

阅读 2.1k
2 个回答
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)
  }
}

type IProps = {
    xxx:boolern
    OnChange:Function
} &({
    xxx:true
    OnChange(a:typeof a, b:typeof b):void
} | {
    xxx:false
    OnChange( b:typeof b, a:typeof a):void
})

function name({xxx,OnChange}:IProps){
    let a,b:any;

    if(xxx)
        OnChange(a,b)
    else
        OnChange(b,a)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题