Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何创建条件参数类型?_Javascript_Typescript_Types - Fatal编程技术网

Javascript 如何创建条件参数类型?

Javascript 如何创建条件参数类型?,javascript,typescript,types,Javascript,Typescript,Types,一个函数需要两个参数、一个字符串和一个回调。根据第一个参数,第二个参数的类型可能会改变 function (eventName: string, fn: (dto?: any) => unknown) {} 在上面的示例中,如果eventName是注册我希望dto成为某个对象(接口)。您可以重载函数: function named(eventName: "signup", fn: (dto: { /*...*/ }) => unknown); functio

一个函数需要两个参数、一个字符串和一个回调。根据第一个参数,第二个参数的类型可能会改变

function (eventName: string, fn: (dto?: any) => unknown) {}

在上面的示例中,如果
eventName
注册
我希望
dto
成为某个对象(接口)。

您可以重载函数:

 function named(eventName: "signup", fn: (dto: { /*...*/ }) => unknown);
 function named(eventName: string, fn: (dto?: any) => unknown) {
    // but only one may have a body
 }

您不能定义条件类型,因为typescript有一个相当静态的编译器和类型检查器

要解决类型检查器问题,可以使用类型联合

FirstType && SecondType

此外,您还可以使用具有预定义类型的对象中的值:

function (eventName: string, value: {first?: FirstType, second?: SecondType}) {}
因此,在检查第一个参数后,可以输入第一个或第二个值

最好的方法是将这个逻辑分成不同的函数,并从第三个函数调用它们,这将是一种路由器

function handleSignup(value: SignupEvent) {}

function handleNonsignup(value: NonSignupEvent) {}

function (eventName: string, value: any) {
    //You do not know the actual type of this argument here, so any is rather fine(but not perfect choice)
    if (eventName === 'signup') {
        handleSignup(value)
    } else {
        handleNonsignup(value)
    }
}
function handleSignup(value: SignupEvent) {}

function handleNonsignup(value: NonSignupEvent) {}

function (eventName: string, value: any) {
    //You do not know the actual type of this argument here, so any is rather fine(but not perfect choice)
    if (eventName === 'signup') {
        handleSignup(value)
    } else {
        handleNonsignup(value)
    }
}