簡體   English   中英

TypeScript中的泛型類型反射

[英]Generic type reflection in TypeScript

在以下情況下是否可以確定通用類型T

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>());

由於這些類型在編譯期間會被擦除,因此在代碼運行時它們將不可用。

這意味着您必須進行少量復制...

class MyClass {
    constructor() {
    }

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

class MyClass2 {
}

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

在這種情況下,您最終會得到answer function ,但是您可能想要MyClass2

我寫了一個如何在TypeScript中獲取運行時類型名稱示例,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM