Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript global enum that gets inlined on compilation

I have an enum that gets used almost everywhere in my project. I don't want to import it in each and every file. Is there a way to define an enum in the .d.ts file so that it gets inlined when compiled to js?

in my types/global.d.ts file I tried

declare enum MessageType {
    DIRECT = 'direct',
    FORWARDED = 'forwarded'
}

When I run the app I get MessageType.DIRECT is not defined error somewhere in my code, where I try to use it. I never imported this enum because tslint recognizes it and the autocompletion works as well.

I also tried declare const enum ... with the same effect.

Any ideas?

like image 476
George Avatar asked Oct 27 '22 19:10

George


2 Answers

By using declare, you've created an ambient enum, which mean you're defining the shape of an existing object, so this is just generating types, not an actual object.

If you remove declare, it'll create both the type for the enum, and the object

https://www.typescriptlang.org/docs/handbook/enums.html has more detail on ambient enums

like image 192
Richard Avatar answered Jan 02 '23 21:01

Richard


The declare keyword indicates that the associated function, class, etc. is defined elsewhere and TSC should not emit any runtime code for the object.

I would recommend either placing this in some typescript file other than a declaration file (.d.ts) and removing the declare or include some kind of equivalent code to be used at runtime in a .js file.

like image 38
p.s.w.g Avatar answered Jan 02 '23 20:01

p.s.w.g