I am wondering is there anyt c# equivalent for TypeScript's never type
example I write this code in TS I will have a build time error.
enum ActionTypes {
Add,
Remove
}
type IAdd = {type: ActionTypes.Add};
type IRemove = {type: ActionTypes.Remove};
type IAction = IAdd | IRemove;
const ensureNever = (action: never) => action;
function test(action: IAction) {
switch (action.type) {
case ActionTypes.Add:
break;
default:
ensureNever(action);
break;
}
}
error is: Argument of type 'IRemove' is not assignable to parameter of type 'never'.
This is very useful when someone change the logic in one file and I want to be sure this new case is handled everywhere.
Is there any way to do this in c#? (I googled around but I did not find anything)
This is what I have so far...
using System;
class Program
{
private enum ActionTypes
{
Add,
Remove
}
interface IAction {
ActionTypes Type { get; }
}
class AddAction : IAction
{
public ActionTypes Type
{
get {
return ActionTypes.Add;
}
}
}
class RemoveAction : IAction
{
public ActionTypes Type
{
get
{
return ActionTypes.Remove;
}
}
}
static void Test(IAction action)
{
switch (action.Type)
{
case ActionTypes.Add:
Console.WriteLine("ActionTypes.Add");
break;
default:
// what should I put here to be sure its never reached?
Console.WriteLine("default");
break;
}
}
static void Main(string[] args)
{
var action = new RemoveAction();
Program.Test(action);
}
}
I want to be sure I have an error at build time not run time.
Unfortunately, I don't think the C# compiler is smart enough to do that. Even if you throw a new exception in the default case in the switch statement on action.Type, no compile-time error will appear regarding the missing ActionTypes.Remove case.
I found this MSDN blog post that says about the never type that it's "unlikely that it will become a feature of mainstream CLR languages."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With