簡體   English   中英

有什么方法可以強制執行未實例化類的類型嗎?

[英]Is there any way to enforce the type of an uninstantiated class?

Typescript中有什么方法可以強制執行未實例化類的類型?

在下面,我要強制執行以下操作:只有擴展了Repository類才能傳遞給addRepository方法,但我不想在傳遞時實例化該類(其構造函數只能由服務容器調用)。

有什么辦法嗎?

import { Repository } from '../repositories/repository';

class Factory {

  addRepository(repositoryClass: Repository) /* <- seriously what can go here? */ { }
}

class UserRepository extends Repository {

}

let factory = new Factory();

factory.addRepository(UserRepository); // throws error

您可以使用typeof運算符:

class Factory {
  addRepository(repositoryClass: typeof Repository) { }
}

暫無
暫無

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

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