Reputation: 2643
I recently added typings to a private npm module.
One of the module's exported type is the following enum:
export enum ServerResponseCode {
LoginFailed: 'loginFailed',
LoginExpired: 'loginExpired'
}
Then it is imported by another typescript project and used as following:
import { ServerResponseCode } from 'private-module'
if(response.code === ServerResponseCode.LoginExpired)
This code does not raise any compilation errors, but on runtime I get an error: 'Cannot read property LoginExpired of undefined'
Why is this happening and how could I fix it?
Upvotes: 5
Views: 1467
Reputation: 2643
Solution is to simply export a const enum in the type declaration file of private-module:
export const enum ServerResponseCode {
LoginFailed: 'loginFailed',
LoginExpired: 'loginExpired'
}
Short explanation from this stackoverflow thread:
The enum is defined as const
so that any reference to its elements are inlined (by ts compiler), this way avoid a run time lookup to the ServerResponseCode
object which is actually undefined
(because .d.ts files do not result in any JS).
Upvotes: 3