2017-11-19 1 views
1

저는 A 클래스의 fetch 메서드를 오버라이드하는 기본 클래스 A와 확장 클래스 B를가집니다. 그러나 B.fetch()를 호출하면 'baseclass'가 기록됩니다. 왜 B에 정의 된 메소드 정의를 호출하지 않습니까?타이프 스크립트 메서드 무시가 작동하지 않습니다.

 class A { 
     protected apiPath: string = '' 
     static async fetch (id = null, Model = this, apiPath = this.apiPath): Promise<any> { 
      console.log('basefetch') 
      let url = apiPath 
      if(id) url += '/' + id 
      let { data } = await axios.get(url) 
      let item: any = new Model(data) 
      return item 
     } 
    } 

    class B extends A { 
     static async fetch(id = null, Model = this, apiPath = this.apiPath): Promise<Data> { 
      console.log('childfetch') 
      let {data} = await axios.get(apiPath) 
      if (typeof data.challenge.participating == 'undefined') { 
       data.challenge.participating = null 
      } 
      if (typeof data.challenge.progress == 'undefined') { 
       data.challenge.progress = null 
      } 
      return new Model(data) 
     } 

class SomeOtherModule { 
    async doSomething() { 
     let b: B = await B.fetch() 
    } 
} 
+0

당신이 클래스 B에서'fetch' 메소드를 호출하는 방법? 그 부분을 게시 할 수 있습니까? – Niladri

+0

@Niladri 나는 그것을 추가했다 – Chris

+0

@Chris'B.fetch()'는'Promise '를 반환하고'B' 타입의'b'에 할당 될 수 없다. 'apiPath'가 정적이 아니기 때문에 메서드 서명의'apiPath = this.apiPath'도 컴파일되지 않기 때문에 이것은 모두 의사 코드라고 가정합니다. 쇼가 자신의 행동을 나타내는 plunkr을 제공 할 수 있습니까? – zgue

답변

0

정적 멤버가 생성자 함수에 할당됩니다. B.fetch(...)과 같이 호출해야합니다.

귀하의 예제 클래스에 대한 JS 코드를 결과 :

var A = (function() { 
    function A() { 
    } 
    A.fetch = function() { 
     console.log("A fetch"); 
    }; 
    return A; 
}()); 
var B = (function (_super) { 
    tslib_1.__extends(B, _super); 
    function B() { 
     return _super !== null && _super.apply(this, arguments) || this; 
    } 
    B.fetch = function() { 
     console.log("B fetch"); 
    }; 
    return B; 
}(A)); 

이것은 당신이 A.fetch(...)라는 것을 의미한다.

+0

실제로 B.fetch()를 호출합니다 (업데이트 된 질문 참조). – Chris

0

방법 서명이 다릅니다. A에서는 Promise<any>을 반환하지만 B에서는 Promise<Data>을 반환합니다.

당신은 당신이 확실히 무엇을하려고 작업 할 수 this snippet에서 볼 수

class A { 
    static fetch(): string { 
    return 'basefetch'; 
    } 
} 

class B extends A { 
    static fetch(): any { 
    return 'childfetch'; 
    } 
} 

let aVal: string = A.fetch(); 
console.log(`aVal: ${aVal}`); 

let bVal: string = B.fetch(); 
console.log(`bVal: ${bVal}`); 
관련 문제