Programing

TypeScript 함수 오버로딩

lottogame 2020. 5. 5. 19:33
반응형

TypeScript 함수 오버로딩


TypeScript 언어 사양의 섹션 6.3에서는 함수 오버로드에 대해 설명하고이를 구현하는 방법에 대한 구체적인 예를 제공합니다. 그러나 내가 이와 같은 것을 시도하면 :

export class LayerFactory { 

    constructor (public styleFactory: Symbology.StyleFactory) { }

    createFeatureLayer (userContext : Model.UserContext, mapWrapperObj : MapWrapperBase) : any {           
         throw "not implemented";
    }                 

    createFeatureLayer(layerName : string, style : any) : any {
        throw "not implemented";
     }        

}

함수 매개 변수의 유형이 다르더라도 중복 식별자를 나타내는 컴파일러 오류가 발생합니다. 두 번째 createFeatureLayer 함수에 추가 매개 변수를 추가하더라도 여전히 컴파일러 오류가 발생합니다. 아이디어주세요.


두 함수가 JavaScript로 컴파일 될 때 서명이 완전히 동일하기 때문일 수 있습니다. JavaScript에는 유형이 없으므로 동일한 개수의 인수를 사용하는 두 개의 함수를 만듭니다. 따라서 TypeScript는 이러한 함수를 만들 수 없도록 제한합니다.

TypeScript는 많은 매개 변수를 기반으로 오버로드를 지원하지만 OO 언어와 비교하면 따라야 할 단계가 약간 다릅니다. 다른 SO 질문에 대한 답변으로 누군가가 좋은 예를 들어 설명했습니다 : Method overloading? .

기본적으로 우리가하고있는 일은 TypeScript가 컴파일 오류를주지 않도록 하나의 함수와 많은 선언을 만드는 것입니다. 이 코드가 JavaScript로 컴파일되면 구체적인 기능 만 표시됩니다. 여러 인수를 전달하여 JavaScript 함수를 호출 할 수 있으므로 작동합니다.


TypeScript에서 오버로드하면 여러 서명이있는 구현이 하나만 있습니다.

class Foo {
    myMethod(a: string);
    myMethod(a: number);
    myMethod(a: number, b: string);
    myMethod(a: any, b?: string) {
        alert(a.toString());
    }
}

TypeScript에서는 세 가지 오버로드 만 실제 구현이 아니라 메서드 호출의 가능한 서명으로 인식합니다.

귀하의 경우 매개 변수에 공통성이 충분하지 않기 때문에 이름이 다른 두 가지 방법을 개인적으로 사용하기 때문에 메소드 본문에 수행 할 작업을 결정하기 위해 많은 "ifs"가 필요할 수 있습니다.

TypeScript 1.4

TypeScript 1.4부터는 일반적으로 공용체 유형을 사용하여 과부하가 필요하지 않습니다. 위의 예는 다음을 사용하여 더 잘 표현 될 수 있습니다.

myMethod(a: string | number, b?: string) {
    alert(a.toString());
}

유형 a은 " string또는 number"입니다.


함수를 여러 호출 서명이있는 유형으로 선언 하여 오버로드 된 함수를 선언 수 있습니다 .

interface IFoo
{
    bar: {
        (s: string): number;
        (n: number): string;
    }
}

그런 다음 다음을 수행하십시오.

var foo1: IFoo = ...;

var n: number = foo1.bar('baz');     // OK
var s: string = foo1.bar(123);       // OK
var a: number[] = foo1.bar([1,2,3]); // ERROR

함수 의 실제 정의 는 단수 여야하며 인수에서 내부적으로 적절한 디스패치를 ​​수행해야합니다.

For example, using a class (which could implement IFoo, but doesn't have to):

class Foo
{
    public bar(s: string): number;
    public bar(n: number): string;
    public bar(arg: any): any 
    {
        if (typeof(arg) === 'number')
            return arg.toString();
        if (typeof(arg) === 'string')
            return arg.length;
    }
}

What's interesting here is that the any form is hidden by the more specifically typed overrides.

var foo2: new Foo();

var n: number = foo2.bar('baz');     // OK
var s: string = foo2.bar(123);       // OK
var a: number[] = foo2.bar([1,2,3]); // ERROR

As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.

myComponent {
  method(): { console.info("no args"); },
  method(arg): { console.info("with arg"); }
}

Calling:

myComponent.method()

seems to execute the method with arguments, silently ignoring the no-arg version, with output:

with arg

참고URL : https://stackoverflow.com/questions/13212625/typescript-function-overloading

반응형