Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to declare a nest class structure in typescript?

Tags:

typescript

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.

usage:

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

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

like image 523
Corey Alix Avatar asked Nov 21 '12 14:11

Corey Alix


People also ask

How do I create a nested class in TypeScript?

To create nested classes in TypeScript, we can create a static class property in our class. class Foo { static Bar = class {}; } const foo = new Foo(); const bar = new Foo. Bar(); to create the Foo class that has the static Bar property which is set to a class expression.

Does TypeScript support nested classes?

Is it possible to define nested/inner class in typescript? Yes, it is. Go to chapter 3 or 4 if you want to know only nested/inner class.

What is declare class in TypeScript?

declare class is for when you want to describe an existing class (usually a TypeScript class, but not always) that is going to be externally present (for example, you have two . ts files that compile to two . js files and both are included via script tags in a webpage).


1 Answers

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

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,         }     } } 

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.

like image 196
sboisse Avatar answered Sep 23 '22 00:09

sboisse