를 사용하는 것이기 때문에 당신은 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);
에 기반하여 인터페이스를 만족 시키십시오.