George
George

Reputation: 1050

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?

Upvotes: 11

Views: 8010

Answers (3)

mightymagnus
mightymagnus

Reputation: 1

Same problem encountered. Define the enums as constants instead. To get around it, I defined a constants.ts file to store my enums as constants to prevent modification. e.g. In your case:

// constants.ts
export const DIRECT = 'direct'
export const FORWARD = 'forward'

// main.ts
import { DIRECT, FORWARD } from 'constants.ts'
// ... use DIRECT or FORWARD accordingly

If you are using the enum in your type definitions, consider avoid using enum and just specify the values directly e.g.

// types.d.ts
interface User {

    name: string
    role: 'USER' | 'ADMIN' // instead of using enum, define the values that the field can take on

}

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149050

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.

Upvotes: 2

Richard
Richard

Reputation: 1046

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

Upvotes: 5

Related Questions