Establish an enumeration using universally recognized identifiers

I have a JavaScript function that requires a numerical input, as well as some predefined constants at the top level:

var FOO = 1;
var BAR = 2;

The function should only be called using one of these constants.

To ensure type safety in TypeScript, I am attempting to create an interface using an enum:

declare enum MyType {
    FOO,
    BAR
}

interface MyClass {
    process(MyType type);
}

However, when the code is compiled, it outputs MyType.FOO in the JavaScript file. Is there a way to make it output just FOO while still maintaining type safety in TypeScript?

Answer №1

// Version X
const enum _YourType {
    APPLE,
    ORANGE
}
let APPLE = _YourType.APPLE;
let ORANGE = _YourType.ORANGE;

or

// Version Y (if APPLE and ORANGE are imported from another module)
declare const enum _YourType {
    APPLE,
    ORANGE
}
declare let APPLE: _YourType;
declare let ORANGE: _YourType;

Either way,

function myFunction(y: _YourType) { /* ... */ }

myFunction(APPLE); // OK
myFunction('banana'); // Error

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

The exported variable 'SAlert' is utilizing the name 'AlertInterface' from an external module

Utilizing the antd alert component (ts) with styled components import styled from 'styled-components'; import Alert from 'antd/es/alert'; export const SAlert = styled(Alert)` && { margin-bottom: 24px; border-radiu ...

Is there a way to invoke a client-side function from the server?

Is there a way to display an alert at the top of the browser if the SQL query returns empty results? I tried using the "alert" function, but I'm struggling with customizing its appearance. I have a function in my HTML code that triggers an alert, but ...

Angular component name constraints - 'the selector [your component name] is not permissible'

When trying to generate a component using the Angular 6 CLI (version 6.0.7), I encountered an issue. After typing in ng g c t1-2-3-user, I received an error message stating that the selector (app-t1-2-3-user) is invalid. I wondered if there was something ...

Is the Typescript index signature limited to only working with the `any` type?

I recently made changes to my interface and class structure: export interface State { arr : any[]; } export const INITIAL_STATE: State = { arr: [] }; This updated code compiles without any issues. Now, I decided to modify the Interface to incl ...

Script - Retrieve the content of the code element

I am currently developing an extension for VS Code that will enhance Skript syntax support. One challenge I am facing is the inability to select the body of the code block. Skript syntax includes various blocks such as commands, functions, and events, eac ...

The React Hook Form's useFieldArray feature is causing conflicts with my custom id assignments

My schema includes an id property, but when I implement useFieldArray, it automatically overrides that id. I'm utilizing shadcn-ui Version of react-hook-form: 7.45.0 const { fields, append, remove, update } = useFieldArray<{ id?: string, test?: n ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

New Requirement for Angular Service: Subclass Constructor Must Be Provided or Unable to Resolve all Parameters for ClassName (?)

During a recent project, I encountered an issue while working on several services that all extend a base Service class. The base class requires a constructor parameter of HttpClient. When setting up the subclass with autocomplete, I noticed that their con ...

Is there a way for me to retrieve the bodyHeight attribute of ag-grid using public variables or data?

Working on a project using ag-grid community react. The main feature is a scrollable section filled with data, which can range from one piece to millions of pieces. I'm also incorporating a footer component for the grid that needs to adjust its height ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

Leveraging Ionic 2 with Moment JS for Enhanced TimeZones

I am currently working on integrating moment.js with typescript. I have executed the following commands: npm install moment-timezone --save npm install @types/moment @types/moment-timezone --save However, when I use the formattime function, it appears th ...

Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files. The variables I need are stored in src/styles/_variables.scss Here is my tsconfig.json: { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": ".", "allowJs": tr ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Problem with Jasmine in Angular 5 within Visual Studio Code

I am completely new to Angular 5 Unit testing and facing some challenges. Despite installing all @types/jasmine, I am encountering errors in my spec.ts file such as 'describle is not a name' and 'jasmine.createSpyObj does not exist on the ty ...

Utilize the key types of an object to validate the type of a specified value within the object

I am currently working with an object that contains keys as strings and values as strings. Here is an example of how it looks: const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff', } Next, I define a type ...

Avoiding the use of reserved keywords as variable names in a model

I have been searching everywhere and can't find a solution to my unique issue. I am hoping someone can help me out as it would save me a lot of time and effort. The problem is that I need to use the variable name "new" in my Typescript class construct ...

Modify the interface type whilst maintaining the structure of nested objects

In my system, I have a specific interface that outlines the structure of a NoSQL document schema. This includes strings, arrays, nested objects, and more. Here's an example representation: interface IStudentSchema { name: string; age: string; f ...