When working with Angular, if you define an enum to be used as an input property, it willl require you to assign that enum to a class attribute of the parent component and later use it in the html template, else you simply can't us it. An this is just an example.
In that case, a map using as const and also keyof typeof will let you to use the typed string in the html.
The approach that unify the definition for enum and let you use it as is, is the following:
constMyEnum={FIRST:'First',SECOND:'Second',}asconst;typeMyEnum=(typeofMyEnum)[keyoftypeofMyEnum];// ^? type MyEnum = "First" | "Second"declarefunctionfunc(a:MyEnum):void;func(MyEnum.FIRST);// Validfunc('First');// Valid
The real problem is that TypeScript doesn't recognize an enum as a string, even if the enum values are all strings. This aspect of enum make them "weird" in constrast of as const objects.
When working with Angular, if you define an
enumto be used as aninputproperty, it willl require you to assign thatenumto a class attribute of the parent component and later use it in thehtmltemplate, else you simply can't us it. An this is just an example.In that case, a map using
as constand alsokeyof typeofwill let you to use the typed string in thehtml.The approach that unify the definition for
enumand let you use it as is, is the following:The real problem is that TypeScript doesn't recognize an
enumas astring, even if theenumvalues are all strings. This aspect ofenummake them "weird" in constrast ofas constobjects.A better explanation: dev.to/muszynov/something-about-ty...