有什么方法可以在打字稿中声明嵌套类结构? [英] Any way to declare a nest class structure in typescript?

查看:37
本文介绍了有什么方法可以在打字稿中声明嵌套类结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对定义现有框架 (openlayers.d.ts) 感兴趣,但不知道如何表达 OpenLayers.Layer 既是类又是 OpenLayers.Layer.Markers 的命名空间这一事实.我相信这使 Markers 成为层的嵌套类.

I'm interested in defining an existing framework (openlayers.d.ts) but cannot figure out how to express the fact that OpenLayers.Layer is both a class and a namespace for OpenLayers.Layer.Markers. I believe this makes Markers a nested class of Layer.

用法:

l = new OpenLayers.Layer(...); // this is a base class, never do this
m = new OpenLayers.Layer.Markers(...);

您将如何在打字稿中同时声明 Layer 和 Markers 类?

How would you declare both the Layer and Markers class in typescript?

推荐答案

这似乎已在 0.9.1.1 及更高版本中修复.您只需要创建一个与要嵌套类型的类同名的模块,然后将嵌套的类型放入其中.

This seems like it has been fixed in versions 0.9.1.1 and later. You just have to create a module with the same name as the class where you want to nest types, and put your nested types in it.

更具体地说,这就是你的做法:

More concretely, this is how you do it:

declare module a
{
    class b
    {
    }

    module b
    {
        class c
        {
        }
    }
}

var myB = new a.b();
var myC = new a.b.c();

这在使用 export 关键字在打字稿代码中嵌套类型时也有效:

This works as well when nesting types in typescript code with the export keyword:

export module a
{
    export class b
    {
    }

    export module b
    {
        export enum c
        {
            C1 = 1,
            C2 = 2,
            C3 = 3,
        }
    }
}

正如用户@recursive 在下面的评论中提到的,声明的顺序很重要.所以类定义必须位于具有嵌套类型的模块之前.

As mentioned by the user @recursive in the comments below, the order of declaration is important. So the class definition must be located before the module with the nested types.

这篇关于有什么方法可以在打字稿中声明嵌套类结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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