Tuesday 26 August 2014

A [Description] Attribute approach for enums in Typescript


The problem at hand is that I need to use WebAPI services to get data structured in objects and use similar objects client-side in typescript code to structure and manipulate my frontend code. In C# and WebAPI I have the option to use enums:

1 public enum SearchOption
2 {
3 [EnumDescription("Starting With")]
4 StartingWith,
5 [EnumDescription("Contains")]
6 Contains,
7 [EnumDescription("Equal to")]
8 EqualTo,
9 [EnumDescription("Not Equal to")]
10 NotEqualTo
11 }

…which is very convenient because I then could get to the “description” info by reading the attribute for the enum. In typescript on the other hand, there are enums:


1 enum SearchOption {
2 StartingWith,
3 Contains,
4 EqualTo,
5 NotEqualTo
6 }


but no way to define attributes and also no way to access them. So what do we do? We define our enum like this:


1 enum SearchOption
2 {
3 StartingWith = 0,
4 StartingWithDescription = <any>"Starting With",
5 Contains = 1,
6 ContainsDescription = <any>"Contains",
7 EqualTo = 2,
8 EqualToDescription = <any>"Equal To"
9 NotEqualTo = 3,
10 NotEqualToDescription = <any>"Not Equal To"
11 }

This enum definition does not influence enum iteration, the enum items behave as integer values in the same way as before, but additionally there are more items defined that you should not use and only define them and access them in the case that you need the description attribute. To access the description, here is a small static helper class:
1 class EnumHelper {
2 static GetDescription(e: any, id: number): string {
3 return e[e[id].toString() + "Description"];
4 }
5 }
…which will give you access to the “description” of any value for any enum by typing:
1 var q = EnumHelper.GetDescription(SearchOption, 0); /* q is "Starting With" */

4 comments:

  1. Is there any way to automate your descriptions that you have defined: StartingWithDescription = "Starting With" getting this from the C# enumeration itself ? and not redefining it - if your enum in C# changes - then you need to edit this as well - I am looking at one stop shop any ideas on how to do that ?

    ReplyDelete
    Replies
    1. What you see in this post is all client-side code. You would be needing the help of a webservice to deliver the enum values coming from your C# code to the client, then you could use those values to populate the enum instead of hard-coding it.

      Delete
  2. would it not just be easier to have a separate array of strings, using the enum values as a key?
    searchOptionDescription[SearchOption.startingWith] = 'Starting with';
    then the description can be accessed with
    var q = searchOptionDescription[thesearchOptionSelected];

    ReplyDelete