Using enums in definition files

Topics: General, Language Specification
Apr 9, 2014 at 5:22 PM
Hi,

I am having an issue with definition files. I want to declare an enum in its own file, interfaces in a separate definition file, and then class types in their own files. I can use the enum directly from my class types and this allows me to type the object appropriately. However, I would like my interface to contain the proper type information as well. I could type it as a number since that is essentially what the enum represents, however I would prefer it to be typed more strongly.

I have created a small sample in the playground (note the playground example does not work, copy each section of code into a separate typescript file in visual studio): http://www.typescriptlang.org/Playground#src=%2F%2FShapeType.ts%0Aenum%20ShapeType%20%7B%0A%09Circle%2C%0A%09Square%0A%7D%0A%0Aexport%20%3D%20ShapeType%3B%0A%0A%2F%2FShapeInterfaces.d.ts%0Ainterface%20IShape%20%7B%0A%09ID%3A%20string%3B%0A%09Type%3A%20ShapeType%3B%0A%7D%0A%0A%2F%2FShapeBase.ts%0Aimport%20ShapeType%20%3D%20require(%22ShapeType.ts%22)%3B%0Aclass%20ShapeBase%20implements%20IShape%20%7B%0A%09ID%3A%20string%20%3D%20%22%22%3B%0A%09Type%3A%20ShapeType%20%3D%20ShapeType.Circle%3B%0A%09constructor()%20%7B%0A%09%7D%0A%7D%0A%0Aexport%20%3D%20ShapeBase%3B

Any thoughts about how to make this work would be greatly appreciated.

Thanks,
csnance
Coordinator
Apr 9, 2014 at 8:13 PM
Here's one solution:
//ShapeType.ts
enum ShapeType {
    Circle = 9,
    Square
}

export = ShapeType; 

//ShapeInterfaces.d.ts
import ShapeType = require("ShapeType");

export interface IShape {
    ID: string;
    Type: ShapeType;
} 

//ShapeBase.ts
import ShapeType = require("ShapeType");
import ShapeInterfaces = require("ShapeInterfaces");

class ShapeBase implements ShapeInterfaces.IShape {
    ID: string = "";
    Type: ShapeType = ShapeType.Circle;
    constructor() {
    }
}

export = ShapeBase;
Imports that only import type information will be removed by the compiler, so you can use them to get into .d.ts types without affecting the .js output.