TypeScript永不键入C#?

Pet*_*ter 5 c# types typescript

我想知道TypeScript的never类型是否有c#等效项

例如,我在TS中编写此代码,将出现构建时间错误。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是: Argument of type 'IRemove' is not assignable to parameter of type 'never'.

当有人更改一个文件中的逻辑并且我想确保这种新情况在任何地方都可以处理时,这非常有用。

有什么办法可以在C#中做到这一点?(我在Google周围搜索,但未找到任何内容)

这是我到目前为止所拥有的...

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想确保在构建时而不是运行时出现错误。

小智 1

不幸的是,我认为 C# 编译器不够智能,无法做到这一点。即使您在 switch 语句中的 default case 中抛出新的异常action.Type,也不会出现关于缺失ActionTypes.Removecase 的编译时错误。

我发现这篇 MSDN 博客文章谈到了该never类型,“它不太可能成为主流 CLR 语言的一个功能”。