Typescript enum, used from implementation and interfaces
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
Jørgen Tvedt
BY DAY: Working on my Digital Value Network project, which is an organizational collaboration network. Using clever technology, help from Stack Overflow, and some fresh thinking - I hope to introduce a completely new business system approach. https://phil.network BY EVENING: Exercising, reading and obeying the commands of the family.
Updated on July 02, 2022Comments
-
Jørgen Tvedt almost 2 years
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.
-
Jørgen Tvedt almost 8 years@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.