Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a TypeScript like String Literal Union type in C#

Tags:

c#

types

enums

I’m working in C# with some JSON & an API. I'm wondering how to handle something like this.

One of the JSON values is a string that can be one of the following values: “Last_Day”, “Last_Week”, “Last_Month”.

In TypeScript I can do this:

type DateSince = "Last_Day" | "Last_Week" | "Last_Month"

Then I get type hinting like this:

VS Code type hinting suggesting 3 possible values.

If the value is anything but those 3 strings, I get the red squiggle line error. My value is still technically a string as well, which is what I need to use with the JSON API requests and responses.

I have yet to find a great way to do this in C#. Is it even possible to do this in C# with relative ease?

My ideal solution lets me assign a custom type to a variable instead of using a string. This way I don't have to remember the possible string values.

like image 307
mattferderer Avatar asked Mar 06 '23 22:03

mattferderer


2 Answers

In C# you can use Enums.

public enum DateSince
{
    Last_Day ,
    Last_Week,
    Last_Month
}

Usage:

var datesince = DateSince.Last_Day;

Read more about C# Enums

like image 160
vendettamit Avatar answered Apr 27 '23 12:04

vendettamit


As suggested by @PatrickRoberts & @afrazier, the best way is using enums and the Json.NET StringEnumConverter.

[JsonConverter(typeof(StringEnumConverter))]
public enum DateSince
{
    [EnumMember(Value = "LAST_DAY")]
    LastDay,
    [EnumMember(Value = "LAST_WEEK")]
    LastWeek,
    [EnumMember(Value = "LAST_MONTH")]
    LastMonth,
}

Customizing Enumeration Member Values

like image 33
2 revs Avatar answered Apr 27 '23 14:04

2 revs