Does C# have an equivalent to TypeScript's Never type?

Is there a C# equivalent for TypeScript's never type? I am curious about this.

For example, in TypeScript, if I write the following code, I will get 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;
    }
}

The error message will be:

Argument of type 'IRemove' is not assignable to parameter of type 'never'.

The never type in TypeScript is very useful to ensure that all cases are handled when a logic is changed in one file.

I have been searching for a similar feature in C#, but I have not found anything yet.

Here is my attempt at replicating this behavior in C#:

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 am looking for a way to generate a build time error, similar to what happens in TypeScript, rather than having issues at runtime.

Answer №1

It seems that the C# compiler does not have the capability to handle this scenario. Even if a new exception is thrown in the default case of a switch statement on action.Type, there will be no compile-time error indicating the absence of the ActionTypes.Remove case.

I came across a blog post that discusses the unlikelihood of the never type becoming a feature in mainstream CLR languages.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

issue TS2322: The function returns a type of '() => string' which cannot be assigned to type 'string

I have recently started learning Angular 6. Below is the code I am currently working on: export class DateComponent implements OnInit { currentDate: string = new Date().toDateString; constructor() { } ngOnInit() { } } However, I am encounterin ...

Unexpected results from numerous inner sub-queries

Here are the SQL tables: CREATE TABLE [dbo].[My_Employee_Schedule] ( [Emp_Sch_Id] INT IDENTITY (1, 1) NOT NULL, [Schedule_Date] DATETIME NULL, [Start_Time] DATETIME NULL, [End_Time] DATETIME NULL, [Emp_ID] INT NULL, [Job_ID] ...

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...

Building on the foundation of Web API 2.0: Using JavaScriptConverter for Tailored Date Formats

I want to standardize every DateTime object to follow the format "yyyy-MM-dd". Previously, I achieved this by adding the following code snippet to WebApiConfig.cs using JSON.Net: config.Formatters.JsonFormatter.SerializerSettings.Converters.Add( ...

How can we pass the onClick prop from a child component to a parent component in React with Typescript?

Currently, I am utilizing React along with TypeScript. I am curious about the process of passing an event from the parent component to a child component using props. Here is an example for better understanding: parent.tsx const ParentComponent: React.F ...

Having trouble with my React component timer not functioning properly

How can I utilize the Header Component as a Clock timer for my webpage to update every second? Despite searching on Google, I couldn't find examples that match my requirements. Why is the tick() function not functioning properly even though there are ...

The function call with Ajax failed due to an error: TypeError - this.X is not a function

I am encountering an issue when trying to invoke the successLogin() function from within an Ajax code block using Typescript in an Ionic v3 project. The error message "this.successLogin() is not a function" keeps popping up. Can anyone provide guidance on ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

Attempting to interpret and apply information extracted from a JSON document

I'm having trouble importing a JSON file into my Angular TypeScript page file that has this structure: { "latitude": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], "longitude": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], " ...

What are the steps to implementing MSAL in a React application?

Struggling to integrate the msal.js library with react. Post Microsoft login, redirecting to callback URL with code in the query string: http://localhost:3000/authcallback#code=0.AQsAuJTIrioCF0ambVF28BQibk37J9vZQ05FkNq4OB...etc The interaction.status re ...

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

Does manipulating the context before retrieving it within a custom ContextProvider adhere to best practices?

In my React application, I have a custom ContextProvider component called RepositoryContext. This component requires a specific ID to be set inside it in order to perform CRUD operations. Here is a snippet of the code: import React, { Dispatch, PropsWithCh ...

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

"Utilizing TypeScript with React: Creating a window onClick event type

My linter is not happy with the any type for window.onClick. What should be the correct type? import React, { useContext, useState } from 'react'; import { Link } from 'react-router-dom'; import { Global } from '../globalState&apo ...

Why are mustaches not functioning as expected in Vue SFC defined by Vite?

I recently ran into a configuration issue with my vite-config.ts file. export default defineConfig({ ... define: { __PRODUCT__: JSON.stringify("My Product") } In my vue sfc template, I have the following code snippet: <div class="footer"> {{ ...

A method parameter in an MVC controller can be bound to HTML form properties by following these steps

Struggling to bind a controller post method to a basic HTML form on the view. Trying to understand how to populate the parameter and call the method using form data. Controller method: [HttpPost("addcomment")] public JsonResult AddCommen ...

Can type information be incorporated during compilation?

Consider the code snippet below: function addProperties(keys: String[]): Object { // For illustration purposes, this is a specific return return { firstProperty: "first_value", secondProperty: "second_value" }; } export defaul ...

Error message: A Windows Service is triggering a FileLoadException

While working on a Windows service, I encountered an issue every time I attempted to start it: The following exception was displayed: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e08 ...

Angular's Dynamic Reactive Forms

I encountered an issue while using Typed Reactive Forms in Angular 14. I have defined a type that connects a model to a strict form group. The problem arises specifically when utilizing the Date or Blob type. Note: I am working with Angular 14. Error: src/ ...

Is there a way to detect when a value is "re-selected" in a ComboBox?

Currently, I am utilizing a ComboBox to input a text template into a RichEdit control (the template's name is present in the picklist for the ComboBox). Everything functions perfectly except when the user chooses the same value from the list again. I ...