2017-04-25 122 views
0

我想傳遞類的類型信息,同時暗示編譯器指出給定的參數不是類的實例,而是類定義。我怎樣才能做到這一點?如何在類型描述中指定類定義作爲參數類型

import * as Routes from '../routes'; 
import * as Entities from '../entities'; 

export class RouteManager { 
    public router = Router(); 
    private connection = getConnectionManager().get(); 

    constructor() { 
    this.addRoute(Routes.VideoRoute, Entities.Video); 
    } 

    addRoute(routeClass: AbstractRoute<AbstractEntity>, entity: AbstractEntity): void { 
    const instance = new routeClass(entity, this.connection.getRepository(entity)) 
    this.router.get(instance.route, instance.find); 
    } 
} 

在這裏,編譯器會抱怨的new routeClass(entity, this.connection.getRepository(entity))線,因爲它認爲routeClassAbstractRoute<AbstractEntity>一個實例,而不是出口類定義它。

我嘗試過使用AbstractRoute<AbstractEntity>.constructor,但Typescript似乎並不知道這個結構。

+0

您鏈接到這個問題o.O –

+0

對不起! :D http://stackoverflow.com/questions/34698710/defining-typescript-generic-type-with-new –

回答

2

這樣的語法看起來有點奇怪。基本上你可以定義一個使用類似new(...args: any[]) => T的簽名。您當然可以更嚴格地將T替換爲您的班級,將args替換爲constructor簽名。

我建議是這樣的:

class Foo {} 
type Constructor<T> = new(...args: any[]) => T; 

function createFoo(thing: Constructor<Foo>) { return new thing(); } 
+0

它引發以下內容:類型'typeof Video'不能分配到類型'構造函數

+0

在你的例子中沒有'Video'類型,但從它的外觀你多次使用相同的標識符。這也是錯誤告訴你的:*有這個名字的兩種不同類型* PS:這似乎是你的代碼的問題。你能否將我的示例代碼複製/粘貼到代碼庫中,並檢查它是否有效? –

相關問題