例如,以下不会编译(链接到打字稿游乐场示例):
declare class ClassFactory {
constructor();
new(): any;
}
const User = new ClassFactory();
const user = new User();
Run Code Online (Sandbox Code Playgroud)
结果错误:
Cannot use 'new' with an expression whose type lacks a call or construct signature.
Run Code Online (Sandbox Code Playgroud)
我需要额外的注释吗?我如何声明一个元类?我假设它new(): any;被视为类上的原型方法,因此是实例构造模式。
编辑:固定链接
他们是可能的。这是一个快速示例:
declare class User{}
declare interface ClassFactory {
new(): typeof User;
}
declare var ClassFactory: ClassFactory;
const UserClass = new ClassFactory();
const user = new UserClass(); // user has type `User`
Run Code Online (Sandbox Code Playgroud)
new会返回一些东西”,您不能使用class. 因此 interface ClassFactoryvar ClassFactory class不是类的实例,您不能这样做,: User您需要获取类的类型。因此typeof User。这里多次使用的一个关键概念是声明空间的概念。此处涵盖:https : //basarat.gitbooks.io/typescript/content/docs/project/declarationspaces.html
| 归档时间: |
|
| 查看次数: |
912 次 |
| 最近记录: |