2017-03-13 4 views
0

저는 TypeScript에서 아직 완전히 익숙하지 않기 때문에 다른 SO 질문과 설명서가 때로는 혼란 스럽습니다. 나는 이것을 가능한 한 간단하게하려고합니다. 만약 그것이 중복이라면, 저를 가리켜주세요.TypeScript "Function"type과 메소드 서명을 선언하는 것

저는 Function 유형의 멤버를 만드는 것과 단순히 클래스에서 메서드 서명을 정의하는 것 사이에 어떤 차이가 있는지 궁금합니다. 아래의 예를 생각해

export abstract class MyBase { 
    protected abstract method1(); 
    protected abstract method2(): void; 
    protected abstract method3: Function; 
} 

나의 이해는 1과 2 사이의 차이가 2 void가 있거나 어떤 유형 것은이 지정된 상태에서 1 any의 반환 형식을 가지고 있다는 것이다.

1과 3의 차이점이 무엇인지 잘 모르겠습니다. 하나 있습니까?

마지막으로, 1과 2 사이의 관계에서 함수 유형이 일반 일 수없는 이유는 무엇입니까? 우리가 이것을 할 수처럼 즉, (하지만 우리는 할 수 없습니다) 것 같다

protected abstract method4: Function<void>; 

답변

1

내가 1과 3 사이의 차이가 무엇 때문에 확실하지 않다.

큰 차이 :

declare function method1(); //() => any 
declare const method3: Function; // ALL Functions 

매개 변수의 단지 수에 따라 1과 2 사이의 관계를 감안할 때

method1(123); // Error 
method3(123); // Okay 

, 왜 허용하지 않는 기능 유형 제네릭인가?

C#과 동일하지 않습니다. Function은 기본 JavaScript 함수에 이름을 입력합니다.

1

클래스에서이 방법의 차이점

  1. 반환 유형 - 그들의 반환 형식이 다른; method1 & method3의 반환 유형은 any이지만 methods2의 반환 유형은 void입니다. 당신은 tsc --declaration 출력 .d.ts을 사용하고 다음과 같이 선언 파일을 볼 수 있습니다

    export declare abstract class MyBase { 
        protected abstract method1(): any; 
        protected abstract method2(): void; 
        protected abstract method3: Function; 
    } 
    
  2. 동적 대 정적 방법을 - & method2prototype를 통해 열거 할 수 method1하지만 method3 수 없기 때문에 그것은 속성이 아니라 메서드입니다. 또한 Superclass.prototype에 추가 할 수 없습니다. 수퍼 클래스의 생성자에서는 this.method3=()=>{} 만 사용하여 method3을 할당하므로 properties으로 열거 된 동적 메서드와 하위 클래스도 수퍼 클래스에서 동적 메서드를 상속 받지만 super을 사용하여 재정의 할 수는 없습니다. 그렇게하면 TypeScript 컴파일러에서 오류를보고하고 호출하면 런타임 오류가 발생합니다. 제가 말한 것을 설명하는 시험이 있습니다.

제안 : 정적 기법 method3 사용되지 동적 기술을 사용하는 방법을 선언한다. 동적 기술을 사용하는 경우 Superclass 메소드를 재사용 할 수 없습니다.

class Superclass { 
     method1() { 
     } 

     method2 = function() { 
     }; 
     method3 = function() { 

     }; 
    } 
    class Subclass extends Superclass { 
     method1() { 
      super.method1(); 
     } 

     method3 = function() { 
      super.method3(); 
     } 
    } 

    test("methods as property can't be enumerated as prototype",() => { 
     expect(Object.keys(Superclass.prototype)).not.toContain('method3'); 
     expect(Object.keys(new Superclass())).toContain('method3'); 
    }); 
     expect(Object.keys(new Superclass())).toContain('method3'); 

    test("methods as prototype can be enumerated as prototype",() => { 
     expect(Object.keys(Superclass.prototype)).toContain('method1'); 
     expect(Object.keys(new Superclass())).not.toContain('method1'); 
    }); 

    test("methods as property can be inherited in subclass",() => { 
     let it = new Subclass(); 
     it.method2();//works fine 
    }); 

    test("methods as property can't be overrided so you can't call `super`",() => { 
     let it = new Subclass(); 
     expect(()=>it.method3()).toThrow(); 
    });