[英]TypeScript interface to describe class
Is there an interface in TypeScript to describe a class declaration? TypeScript中是否有用于描述类声明的接口?
function module(name: string, classDeclaration: IClass) {
this.classHash[name] = classDeclaration; //example use of class declaration
}
In JavaScript, there are only functions. 在JavaScript中,只有功能。 The
class
keyword in TypeScript & EcmaScript 6 is (for the purposes of this question) sugar for creating a constructor function and filling out its prototype. TypeScript和EcmaScript 6中的
class
关键字(出于此问题的目的)是用于创建构造函数和填写其原型的糖。 Therefore, a generic interface for a “class” in TypeScript is the same as an interface for any constructor function: 因此,TypeScript中“类”的通用接口与任何构造函数的接口相同:
interface Class<T> {
new (...args: any[]): T;
prototype: T;
}
Don't name your function module
, it is a keyword in TypeScript. 不要命名您的功能
module
,它是TypeScript中的关键字。 AFAIK there is no such interface or class but you can create your own interface IClass
which I would strongly recommend. AFAIK没有此类接口或类,但是您可以创建自己的接口
IClass
,我强烈建议您这样做。
An example is: 一个例子是:
interface IClass {}
class MyClass implements IClass {}
class MySecondClass implements IClass {}
function myModule(name: string, classDeclaration: IClass) {
this.classHash[name] = classDeclaration; //example use of class declaration
}
myModule("1", MyClass);
myModule("2", new MyClass());
myModule("3", MySecondClass);
No. I would have expected Function
(or FunctionConstructor
) to be such an interface, but, no. 不,我本来希望
Function
(或FunctionConstructor
)是这样的接口,但是,不会。
What is troubling is that, as expected, in the code below the type returned by typeof
is function
... but function
(lower case f
) is neither a type nor an interface in Typescript. 令人不安的是,正如所料,在下面的代码中,
typeof
返回的类型是function
...,但是function
(小写字母f
)既不是Typescript也不是Typescript的接口。 So the answer has to be no. 因此答案必须为否。
"use strict";
class Hello {
private s: string
constructor(s: string) {
this.s= s
}
public sayHello() {
console.log(`Hello ${this.s}`)
}
}
function instantiate<T>(clazz: any, name: string): T {
console.log(`Type of clazz: ${typeof clazz}`)
return new clazz(name) as any as T
}
instantiate<Hello>(Hello, 'John').sayHello()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.