Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript enum, used from implementation and interfaces

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.

like image 331
Jørgen Tvedt Avatar asked May 09 '16 05:05

Jørgen Tvedt


1 Answers

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

like image 122
basarat Avatar answered Oct 21 '22 01:10

basarat