I'm a web developer with passion for my job. I love sharing my knowledge with fellow developers at my work and by writing articles about web development on personal blog
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.
Great advice, thanks!
Object like
can work the same way as enums.
Could you mention the use cases where this approach is better?
You can change it to:
const enum loadingStateand it will work the same without being smarter givingas constat the end.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...