Is there an interface in TypeScript to describe a class declaration?
function module(name: string, classDeclaration: IClass) {
this.classHash[name] = classDeclaration; //example use of class declaration
}
Is there an interface in TypeScript to describe a class declaration?
function module(name: string, classDeclaration: IClass) {
this.classHash[name] = classDeclaration; //example use of class declaration
}
No. I would have expected Function
(or FunctionConstructor
) to be such an interface, but, no.
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. 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()
In JavaScript, there are only functions. 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. Therefore, a generic interface for a “class” in TypeScript is the same as an interface for any constructor function:
interface Class<T> {
new (...args: any[]): T;
prototype: T;
}
Don't name your function module
, it is a keyword in TypeScript. AFAIK there is no such interface or class but you can create your own interface IClass
which I would strongly recommend.
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.
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. 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()
© 2022 - 2024 — McMap. All rights reserved.