[英]How to get name of generic type T inside service in Angular
需要基於傳遞給該服務的通用類型T在Angular 5服務中創建一些工廠方法。 如何獲得通用類型“ T”的名稱?
@Injectable()
export class SomeService<T> {
someModel: T;
constructor(protected userService: UserService) {
let user = this.userService.getLocalUser();
let type: new () => T;
console.log(typeof(type)) // returns "undefined"
console.log(type instanceof MyModel) // returns "false"
let model = new T(); // doesn't compile, T refers to a type, but used as a value
// I also tried to initialize type, but compiler says that types are different and can't be assigned
let type: new () => T = {}; // doesn't compile, {} is not assignable to type T
}
}
// This is how this service is supposed to be initialized
class SomeComponent {
constructor(service: SomeService<MyModel>) {
let modelName = this.service.getSomeInfoAboutInternalModel();
}
}
您不能僅基於泛型類型實例化一個類。
我的意思是,如果您想要這樣做:
function createInstance<T>(): T {...}
這是不可能的,因為它將轉化為:
function createInstance() {...}
如您所見,無法以任何方式對其進行參數化。
您所能找到的最接近的是:
function createInstance<T>(type: new() => T): T {
return new type();
}
然后,如果您有一個帶有無參數構造函數的類:
class C1 {
name: string;
constructor() { name = 'my name'; }
}
您現在可以執行以下操作:
createInstance(C1); // returns an object <C1>{ name: 'my name' }
這可以完美地工作,並且編譯器會為您提供正確的類型信息。 我之所以使用new() => T
作為type的type
,是為了表明您必須傳遞一個不帶參數的構造函數,該參數必須返回T類型。類本身就是這樣。 在這種情況下,如果您有
class C2 {
constructor(private name: string) {}
}
你也是
createInstance(C2);
編譯器將引發錯誤。
但是,您可以泛化createInstance
函數,使其適用於具有任意數量參數的對象:
function createInstance2<T>(type: new (...args) => T, ...args: any[]): T
{
return new type(...args);
}
現在:
createInstance(C1); // returns <C1>{ name: 'my name'}
createInstance(C2, 'John'); // returns <C2>{name: 'John'}
希望這對您有幫助。
泛型用於類型驗證
class Array<T>{
pop:() => T;
unshift:(v:T) => void;
}
let numbers: Array<number> = ['1212']; //error
let strings: Array<string> = ['1','2','3']; //work
class Product{
}
let products: Array<Product> = [new Product(), new Product()]; //works
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.