Enumerations in Typescript act as interfaces

Utilizing a TypeScript to proto file generator library (ts-protoc-gen), results in the generation of the following code snippet for enums:

export interface AnimalTypeMap {
    Dog: 0;
    Cat: 1;
    Fish: 2;
    Bird: 3;
}

export const AnimalType: AnimalTypeMap;
  1. What is the recommended way to utilize this generated code?
if (arg === AnimalType.Bird) {} // **ERROR**: Variable 'AnimalType' is used before being assigned
if (arg === AnimalTypeMap.Bird) {} // **ERROR**:'AnimalTypeMap' only refers to a type, but is being used as a value here
  1. Is it possible for a constant to be exported without initialization like this?

Answer №1

To update your enum class in TypeScript, follow the example below:

 export interface AnimalTypeMap 
     {
    Dog: Dog;
    Cat: Cat;
    Fish: Fish;
    Bird: Bird;
     }

When working on the backend, implement the following:

 [JsonConverter(typeof(StringEnumConverter))]
    public enum AnimalTypeMap {
{
        Dog: 1;
        Cat: 2;
        Fish: 3;
        Bird: 4;
         }

In C#, this is how you would do it.

Answer №2

If you want to make use of both --ts-out and --js-out options in protoc, here's a code snippet that has worked for me:

import {AnimalType, AnimalTypeMap} from "./generated/AnimalType_pb"
const animalType:AnimalTypeMap[keyof AnimalTypeMap] = AnimalType.Bird;

Although this solution may not be the most intuitive, it does get the job done. However, I believe there might be a better approach.

UPDATE: A more user-friendly option is available in a fork called https://github.com/gnomesley/ts-protoc-gen, which generates standard TypeScript enums.

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

How can a variable be used to assign a date value to an Angular Material datepicker?

Is there a way to modify the date of an item in an array? I've encountered an issue when attempting to input the selected object's date into the Material datepicker. Strangely, it seems to function properly if you manually type in a date as a str ...

The Angular application has encountered a stack overflow due to exceeding the maximum

./src/main.ts - An issue occurred: The module build process failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js): Error: Maximum call stack size exceeded import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; { App ...

Efficient approach for combining list elements

I have a collection of content blocks structured like this: interface Content{ type: string, content: string | string[] } const content: Content[] = [ { type: "heading" content: "whatever" }, { type: "para&quo ...

Steps to integrating an interface with several anonymous functions in typescript

I'm currently working on implementing the interface outlined below in typescript interface A{ (message: string, callback: CustomCallBackFunction): void; (message: string, meta: any, callback: CustomCallBackFunction): void; (message: string, ...m ...

Update ngx-datatable when the user clicks on a different directive

My issue involves a Side Navigation with a docking feature and a data table in the Main View. When I undock the side navigation, the data table does not recalculate automatically, leaving empty space where the Side Navigation was. This requires me to manua ...

Showing the Enum name rather than the value in an Angular HTML template for a bound Typescript Interface

After retrieving an array of objects with various properties from a .NET Controller, I am utilizing the following Typescript code: import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Co ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

Ensuring type safety while dynamic object property setting in VueX Store using TypeScript

Currently, I am working on a Vue 3 project with TypeScript, transitioning from JavaScript, and keeping it simple without using complex plugins for Vuex store. I have a mutation that dynamically sets various properties of an order object to eliminate the ne ...

TypeScript: additional information on the properties of an interface

Attempting to develop a framework that enables meta on interface fields. Consider the following example: function path(path) {} interface ITwoProps { @path('some/path') stringProp: string; @path('different/path') boolProp: boolean ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

Creating and managing global context with useReducer in TypeScript and React

One issue that I am facing is with the route containing a login and logout button, where the browser error states 'Property 'dispatch' does not exist on type '{}'. (home.tsx) import React, { useContext, useEffect, useRef, use ...

Guide to setting up value observation in React Context for optimal functionality

Imagine a scenario where there is a Parent Component that provides a Context containing a Store Object. This Store holds a value and a function to update this value. class Store { // value // function updateValue() {} } const Parent = () => { const ...

How can I integrate the "FETCH FIRST n ROWS ONLY" feature into my Kysely DB query builder?

For my projects that are based on TypeScript, Prisma is my go-to DB toolkit. However, I recently encountered a project where Kysely, a type-safe DB query builder, was being used. I'm currently trying to create a query with Kysely that can handle keys ...

Discover how to access and manipulate JSON files in an Angular application using

Currently, I am diving into learning TypeScript with Angular and I'm interested in reading a JSON file. The structure of my JSON file is as follows: { "nb": "7", "extport": "1176",, "REQ_EMAIL": ...

Is it possible for Typescript to automatically determine the exact sub-type of a tagged union by looking at a specific tag value?

I have an instance of type Foo, which contains a property bar: Bar. The structure of the Bar is as follows: type ABar = {name: 'A', aData: string}; type BBar = {name: 'B', bData: string}; type Bar = ABar | BBar; type BarName = Bar[&apos ...

The prototype's function doesn't pause for anything, carrying out its duty in a continuous cycle

I have been attempting to enhance the prototype of an object by adding an asynchronous function to be called later on. Here is my approach: const ContractObject = Object; ContractObject.prototype['getBalance'] = async function(userId: number ...

Manage input from either mouse or touch events based on the event type

I've encountered a challenge with my general handler function that processes both mouse and touch events. Despite my efforts, Typescript keeps issuing errors due to the distinction between mouseEvent and touchEvent. function handleStopDrag(e: MouseEv ...

Warning in TypeScript when attempting to modify a single state property within a React component

Imagine we have a simple react Component: import React, { Component } from 'react'; interface IState { a: boolean; b: string; c: number; } class Test extends Component<{}, IState> { state = { a: true, b: 'value' ...