问题
We are using TypeLite to generate Enums in TypeScript.
C#:
[TsEnum(Module = "CustomEnum")]
public enum TSEnum {
None,
Test
}
http://type.litesolutions.net/
Generates this code in a file called Enums.ts:
namespace CustomEnum {
export enum TSEnum {
None = 0,
Test =1
}
}
As default TypeLite generates a const enum
but in order to be able to get the names of the TypeScript enum entry const
has been removed. This was done by editing TypeLite.Net4.tt
and changing:
<# var ts = TypeScript.Definitions()
.WithReference("Enums.ts")
.ForLoadedAssemblies();
#>
To this:
<# var ts = TypeScript.Definitions()
.WithReference("Enums.ts")
.ForLoadedAssemblies()
.AsConstEnums(false);
#>
https://bitbucket.org/LukasKabrt/typelite/issues/96/allow-option-of-export-const-enum-to-be
https://www.typescriptlang.org/docs/handbook/enums.html#const-enums
I do not get any compile warning but at runtime I get the following error
Uncaught ReferenceError: TSEnum is not defined
Code generating error:
console.log(CustomEnum.TSEnum[CustomEnum.TSEnum.None]);
Or simply:
console.log(CustomEnum.TSEnum.None);
https://stackoverflow.com/a/36743651/3850405
If I however write it like this everything works:
enum TSEnum {
None = 0,
Test = 1,
}
console.log(TSEnum[TSEnum.None]);
What can I do to fix this? I'm using webpack
for bundling if this could affect something. I have tried to import the Enums but it does not make any difference.
import '../../../Scripts/Enums';
If I manually entered export
to CustomEnum
and then imported the enum the code worked but the declarations that used CustomEnum.TSEnum
in TypeLite.Net4.d.tt
could no longer find the property.
import { TouchPoint } from '../../../Scripts/Enums';
Enums.ts:
export namespace CustomEnum {
export enum TSEnum {
None = 0,
Test =1
}
}
回答1:
Could not find a good solution so I decided to create a new enum object that can be used in front end. I removed .AsConstEnums(false)
from TypeLite.Net4.d.tt
and created the following code:
export enum TSEnumObject {
None = CustomEnum.TSEnum.None,
Test = CustomEnum.TSEnum.Test
}
console.log(TSEnumObject[TSEnumObject.None]);
来源:https://stackoverflow.com/questions/48418792/typelite-typescript-enum-runtime-error-uncaught-referenceerror-tsenum-is