7

I have the following, in CommandEnum.ts:

export enum CommandEnum {
    createProject,
    renameProject,
    hablaBabla
}

in a module which I am able to reference from implementation code, using

import {CommandEnum} from '../server/contracts/CommandEnum'

let x = CommmandEnum.hablaBabla

The enum file is compiled into a javascript function with export logic, in CommandEnum.js.

This now works fine, but I want to reference this enum in my interfaces as well, I try:

/// <reference path="../contracts/CommandEnum.ts" />
namespace ValueTypes {

    export interface Command {
        type : CommandEnum;
        referenceId : string;
    }
}

Now, this reference does not import the CommandEnum type, but some of the other combinations of modules / namespace / export default I have tried does. I can get the reference syntax to work, but not the module syntax and the other way around - but not both.

Is this actually possible? Using an enum from a pure definitions interface file seems like a very common scenario. But when the interface is implemented the enum must be available in "function form" and these two models does not seem to combine?

I had the same problem with classes, which I wanted to namespace, .Net-style - which I had to give up. Classes, however, are not referenced in my interfaces - enums are.

I work with node.js and compile to individual files, not a single concated output.

1 Answer 1

4

This now works fine, but I want to reference this enum in my interfaces as well

You can move stuff from a module into the global namespace use declare global

E.g. myEnumGlobalDeclare.ts

import {MyEnum as MyEnumModule} from "./myEnum";
declare global {
   declare var MyEnum: typeof MyEnumModule;
}

E.g. myEnumGlobalDefine.ts

import {MyEnum as MyEnumModule} from "./myEnum";
MyEnum = MyEnumModule;

Or something similar ^. Of course this means your runtime should support global augmentation e.g. in nodejs you need to use globals and in browsers window.

More

I definitely do not recommend going down this path. Instead create a global types.ts module and just use that everywhere. E.g. alm has this file : https://github.com/alm-tools/alm/blob/master/src/common/types.ts

Sign up to request clarification or add additional context in comments.

1 Comment

@baserat, thank you. I take it you recommend a single contract file for the project / subdomain - with all enums and interfaces? This would probably solve the problem but I believe it could lead to very heavy type files in some projects... For now I'll just use strings in the interfaces and enums in the implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.