TypeScript接口描述类 [英] TypeScript interface to describe class

查看:126
本文介绍了TypeScript接口描述类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript中是否有一个用于描述类声明的接口?

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
}

推荐答案

否.我本来希望Function(或FunctionConstructor)是这样的接口,但是,没有.

No. I would have expected Function (or FunctionConstructor) to be such an interface, but, no.

令人困扰的是,按预期,在下面的代码中,typeof返回的类型是function ...,但是function(小写的f)既不是Typescript也不是Typescript的接口.因此答案必须为否.

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()

这篇关于TypeScript接口描述类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆