2014-11-18 4 views
1

다음 시나리오에서 일반 형식 T을 확인할 수 있습니까?TypeScript의 일반 형식 반영

class MyClass { 
    constructor() { 
    } 

    GenericMethod<T>(): string { 
     return typeof(T);   // <=== this is flagged by the compiler, 
            //  and returns undefined at runtime 
    } 
} 

class MyClass2 { 
} 

alert(new MyClass().GenericMethod<MyClass2>()); 

답변

3

컴파일 중에 유형이 지워지기 때문에 코드를 실행할 때 유형을 사용할 수 없습니다. 이 경우

이것은 당신이 작은 중복을해야 의미 ...

class MyClass { 
    constructor() { 
    } 

    GenericMethod<T>(targetType: any): string { 
     return typeof(targetType); 
    } 
} 

class MyClass2 { 
} 

alert(new MyClass().GenericMethod<MyClass2>(MyClass2)); 

, 당신은 대답 function와 끝까지,하지만 당신은 아마 MyClass2을 원했다.

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

class Example { 
} 

class AnotherClass extends Example { 
} 

var x = new Example(); 
alert(Describer.getName(x)); // Example 

var y = new AnotherClass(); 
alert(Describer.getName(y)); // AnotherClass 
:

I는 다음과 같이 보이는, example of how to get runtime type names in TypeScript을 작성했습니다