TypeScript module and class simultaneously?

2019-05-09 01:20发布

问题:

I am currently trying to build a TypeScript definition file for OpenLayers.

The problem is that in OpenLayers there are certain classes that would translate to both a module and a class in TypeScript.

For example there is the Protocol class in module OpenLayers and there is a class Response in module OpenLayers.Protocol.

How could I model that in TypeScript? Can I make Protocol a class and define the Response class as a inner class that is exported? How would you go about solving that problem?

回答1:

Declare Response as a static field of Protocol with a constructor type, returning an interface that defines the Response class:

declare module OpenLayers {
    export interface IProtocolResponse {
        foo(): void;
    }

    export class Protocol {
        static Response: new () => IProtocolResponse;
    }
}

var response = new OpenLayers.Protocol.Response();
response.foo();

Edit:

Or as Anders points out in this discussion list question, you can have multiple constructors for the inner class in this way:

declare module OpenLayers {
    export interface IProtocolResponse {
        foo(): void;
    }

    export class Protocol {
        static Response: {
            new (): IProtocolResponse;
            new (string): IProtocolResponse;
        };
    }
}

var response = new OpenLayers.Protocol.Response('bar');
response.foo();

The main downside of both approaches is that you cannot derive a class from OpenLayers.Protocol.Response.



回答2:

Here is my updated answer, which I hope helps - it should get you started on defining OpenType:

declare module OpenType {
   export class Protocol {
       constructor();
       Request;
   }
}

var x = new OpenType.Protocol();
var y = new  x.Request();
var z = x.Request;