2014-01-08 5 views
2
export class Base { 
    static getSomething():typeof this //<-- change this? 
    { 
     var type = typeof this; 
     return new this['type'](); 
    } 
} 
export class Foo extends Base { 
    publicVar:string = 'getThis!'; 
} 

var foo:Foo = Foo.getSomething(); 
var success:string = foo.publicVar; 

컴파일러에서 Foo.getSomething이 Foo가 아니라 Base를 반환하기 때문에 위 오류가 반환됩니다. 컴파일러가 Foo를 반환 할 것이라는 것을 Foo의 정적 함수라고 부를 수있는 또 다른 방법이 있는지 궁금합니다.typescript에서 함수를 확장하는 클래스의 형식을 반환 할 수 있습니까?

은 당연히 나는 푸에 명시 적으로 구현할 수있다, 따라서 자료를 확장 모든 클래스에서, 아니면 단순히 배역 수 :

var foo:Foo = <Foo> Foo.getSomething(); 

하지만 중 하나를 할 필요가없는 방법이 있는지 궁금 해서요을 나는이 방법 많이

답변

4

를 사용하는 것이기 때문에 당신은 Liskov 대체 원칙을 따른다면 그 일에, 유형 어설

없애하기, 당신은 유형의 주장이 필요하지 않습니다.

코드 예제 1 - 대체 가능한 객체 ... 또는

module Test { 
    export class Base { 
     publicVar: string = 'base'; 

     static getSomething() : Base { 
      //... read on... 
     } 
    } 

    export class Foo extends Base { 
     publicVar:string = 'getThis!'; 
    } 
} 

// No <Foo> type assertion needed 
var foo: Test.Foo = Test.Foo.getSomething(); 

alert(foo.publicVar); 

, 당신은 당신에게 publicVar 속성이 그를 반환합니다 반환 된 객체를 알려주는 interface를 만들 수 있습니다 ...

코드 예제 2 - 인터페이스

module Test { 
    export interface IPublicVarable { 
     publicVar: string; 
    } 

    export class Base { 
     static getSomething() : IPublicVarable { 
      //... read on... 
     } 
    } 

    export class Foo extends Base { 
     publicVar:string = 'getThis!'; 
    } 
} 

// No <Foo> type assertion needed 
var foo: Test.IPublicVarable = Test.Foo.getSomething(); 

alert(foo.publicVar); 

실제 유형

얻기

이것은 다른 문제를 해결하지 못합니다. var type = typeof this;은 런타임에 예상 한 것을 제공하지 않습니다. Function이 아닌 것은 Foo입니다.

형식 이름을 얻으려면 실제로 Test.Foo 형식 이름을 사용하는 경우 Function인데 다시는 좋지 않습니다. 따라서 두 가지 하위 클래스를 모두 사용하는 불완전한 예제가 있습니다. 내 Obtaining a Class Name at Runtime example :

module Test { 
    export class Describer { 
     static getName(inputClass) { 
      var funcNameRegex = /function (.{1,})\(/; 
      var results = (funcNameRegex).exec((<any> inputClass).constructor.toString()); 
      return (results && results.length > 1) ? results[1] : ""; 
     } 

     static getInstanceOf(inputClass) : Test.IPublicVarable { 
      var name = Describer.getName(inputClass); 
      return new Test[name](); 
     } 
    } 

    export interface IPublicVarable { 
     publicVar: string; 
    } 

    export class Base { 

    } 

    export class Foo extends Base { 
     publicVar:string = 'foo class'; 
    } 

    export class Bar extends Base { 
     publicVar:string = 'bar class'; 
    } 
} 

var a: Test.Base = new Test.Foo(); 
var x: Test.IPublicVarable = Test.Describer.getInstanceOf(a); 
alert(x.publicVar); 

var b: Test.Base = new Test.Bar(); 
var y: Test.IPublicVarable = Test.Describer.getInstanceOf(b); 
alert(y.publicVar); 
에 기반하여 인터페이스를 만족 시키십시오.
관련 문제