Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.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 重载函数在数量和数量上有所不同;使用联合类型的Typescript中的参数类型_Javascript_Oop_Typescript_Overloading_Union Types - Fatal编程技术网

Javascript 重载函数在数量和数量上有所不同;使用联合类型的Typescript中的参数类型

Javascript 重载函数在数量和数量上有所不同;使用联合类型的Typescript中的参数类型,javascript,oop,typescript,overloading,union-types,Javascript,Oop,Typescript,Overloading,Union Types,我试图重载一个函数,它有两个重载,如下所示 getData(): MyModel getData<T>(type:string):T getData(type:number): MyModel getData<T>(type:string):T getData<T>(type: number|string): MyModel:T { //implementation } getData(): MyModel getData<T>(type:s

我试图重载一个函数,它有两个重载,如下所示

getData(): MyModel
getData<T>(type:string):T
getData(type:number): MyModel
getData<T>(type:string):T
getData<T>(type: number|string): MyModel:T {
 //implementation
}
getData(): MyModel
getData<T>(type:string):T
案例2:(问题:在这种情况下如何使用联合类型)

当函数参数的数量和类型不同时,如下所示

getData(): MyModel
getData<T>(type:string):T
getData(type:number): MyModel
getData<T>(type:string):T
getData<T>(type: number|string): MyModel:T {
 //implementation
}
getData(): MyModel
getData<T>(type:string):T
getData():MyModel
getData(类型:字符串):T
问题

  • 如何在
    案例2中使用
    联合类型
  • 如果无法使用联合类型,则说明如何重载这些函数(使用Typescript)

  • 您需要将参数设置为可选参数,并为返回类型使用联合类型:

    class MyClass {
        getData(): MyModel;
        getData<T>(type: string): T;
        getData<T>(type?: string): MyModel | T {
            // implementation
        }
    }
    
    class-MyClass{
    getData():MyModel;
    getData(类型:字符串):T;
    getData(类型?:字符串):MyModel | T{
    //实施
    }
    }
    

    ()

    但它并不像在博客()中提到的那样,在intellisence中分别显示这两个重载。一定是你的ide里有东西。