Utilize enums to implement a static member in a class

Having this code snippet:

declare enum Snacks {
  APPLE = 'APPLE',
  CARROT = 'CARROT',
  JERKY = 'JERKY'
}

declare abstract class ForceSnacks {
  static snack : Snacks
}

export class MySnacks implements ForceSnacks {

  static snack = Snacks.APPLE;

}

Encountering an unfamiliar error:

https://i.sstatic.net/egTmy.png

Does anyone have a solution to resolve the ambient initializer error?

The error message reads as follows:

"Initializers are not allowed in ambient contexts"

Sometimes, another error appears:

"Ambient declaration should have no initializer"

Answer №1

As previously indicated in the comments, the code snippet you're referring to resides within a declaration file—specifically a `.d.ts` file. This is fitting considering the error message you've encountered. Declaration files are designed to contain ambient definitions (e.g. declare class MyFoods {}) as they primarily serve the purpose of outlining the type information of objects rather than providing their actual implementation.

It's worth noting that enforcing static properties, like the one you're trying to implement, isn't currently supported. However, there are alternative approaches available. One option is to utilize a singleton pattern, as demonstrated below:

// implemented in a .ts file
export enum Foods {
  CHERRY = 'CHERRY',
  LETTUCE = 'LETTUCE',
  JERKY = 'JERKY'
}

export interface ForceFoods {
  food: Foods;
}

export class MyFoods implements ForceFoods {
  private static _instance: MyFoods | undefined;

  food = Foods.CHERRY;

  private constructor() {
  }

  static get instance() {
    return this._instance || (this._instance = new MyFoods());
  }
}

// usage example...
MyFoods.instance.food;

Answer №2

declare enum Foods {
  APPLE = 'APPLE',
  CARROT = 'CARROT',
  BEEF = 'BEEF'
}

// class interface
interface ForceFoodsClass {
    food : Foods
    new (): ForceFoods;
}

// instance interface
interface ForceFoods {
    // just to show you will need to add a name property
    name: string;
}


export const MyFoods:ForceFoodsClass = class implements ForceFoods {

  static food = Foods.APPLE;
  name = "Apple delight"
}

Playground

Answer №3

The issue stemmed from having all the code contained within a declaration file (.d.ts). The solution is to move the implementing class to a .ts file:

// index.d.ts

export enum SCEPluginTypes {

  LANGUAGE = 'SCE_LANGUAGE'

}


declare enum Vegetables {
  CARROT = 'CARROT',
  SPINACH = 'SPINACH',
  BEET = 'BEET'
}


declare abstract class PowerVegetables {
  static vegetable : Vegetables
}

// index.ts

import {Vegetables, PowerVegetables} from "./index";

export class MyVegetables implements PowerVegetables {

  static vegetable = Vegetables.CARROT;

}

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 with Angular: ngForm object does not capture selected option

Revise to clean up unnecessary code. Having trouble displaying the selected option when I print the form object to the console. It's showing as undefined. Any guidance on what might be wrong with this code would be appreciated. Let me know if more in ...

Is it feasible to alter the file name while utilizing express-fileUpload library?

Is there a way to modify the file name of an uploaded file on the server side? app.post(URL, (req, res) => { let fileName = req.files.file.name; req.fileUpload; res.statusCode = HTTP_OK; res.send("Good Job") }) The settings I have in uploadF ...

Creating JSON from an array by grouping common values.Would you like another rewrite?

Hey there, I'm facing a small issue with arrays similar to the ones below: const arrays = { 1: [c, u, g], 2: [c, u], 3: [c, u ,f], 4: [c, g], 5: [m, c, g], 6: [u, m] } Each array contains unique values. Now, I'm looking t ...

Dealing with numerous dynamically generated tables while incorporating sorting in Angular: a comprehensive guide

I am faced with a challenge involving multiple dynamically created Angular tables, each containing the same columns but different data. The issue at hand is sorting the columns in each table separately. At present, I have two tables set up. On clicking the ...

Optimizing your use of fromCharCode.apply with Uint8Array in TypeScript 3

I recently came across some code that I inherited which appears like this: String.fromCharCode.apply(null, new Uint8Array(license)); Recently, we updated our project dependencies to TypeScript 3, which raised an error stating: Argument of type 'Ui ...

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

The ng2-intl encounters an issue when trying to resolve symbol values statically

I'm struggling with a common issue and can't seem to find a solution that works. My setup involves Angular 4.2.6 along with ng2-intl 2.0.0-rc.3. Despite trying the following code, I am still facing issues: export function intlFactory(http:Http ...

Finding the width of a div element in Angular 2

I have encountered several posts, but none of them quite achieve what I am trying to do. I am dealing with a table that exceeds the width of the page and, due to certain requirements, I need to measure its width. I attempted: @ViewChild('tableToMea ...

What types should you use for an Axios response in React and TypeScript?

Trying to display a basic user list fetched from an API, which returns the following data: [{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] Struggling to understand how to deal ...

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

Developing a custom React component library using Webpack and Typescript, however encountering issues with Webpack consistently bundling React

I'm currently in the process of developing an external component library using Webpack and TypeScript. Although it compiles without any issues, I encounter an error when attempting to use the library: Invalid hook call. Hooks can only be called ins ...

The dimensions of my Angular app have begun to unexpectedly expand

Currently in the process of developing an Angular application, I've encountered a frustrating issue. Each time I refresh the app using ng serve, the loading time seems to increase gradually. It can now take up to 10 seconds for changes to reflect in t ...

Experiencing difficulties establishing a connection with my NodeJs server socket and TypeScript

I've been struggling to run the code from this post and I really need some help. The code can be found at: https://medium.com/@mogold/nodejs-socket-io-express-multiple-modules-13f9f7daed4c. I liked the code as it seems suitable for large projects, but ...

Save a cookie within the Figma desktop application by utilizing the Node.js API

I'm currently developing a figma plugin using typescript that includes a login module. I've set up the API using Node.js, but I'm encountering an issue with storing cookies. After checking the console in the Figma desktop app, I noticed tha ...

Leverage process.env variables within your next.config.js file

Currently, I have an application running on NextJS deployed on GCP. As I set up Continuous Deployment (CD) for the application, I realized that there are three different deploy configurations - referred to as cd-one.yaml, cd-two.yaml, and cd-three.yaml. Ea ...

`The process of converting Typescript to ES5 through compiling/transpiling is encountering issues`

My current project involves using Webpack and integrating angular2 into the mix. To achieve this, I made adjustments to my setup in order to compile TypeScript. Following a resource I found here, my plan was to first compile TypeScript to ES6 and then tra ...

The date selector is failing to accurately reflect changes in the date objects

I've integrated a date-time picker from this source https://github.com/DanielYKPan/date-time-picker to manage 'beginning' and 'end' date objects (refer to selectedMoments in the TypeScript code) for a date selector. However, when I ...

What is the proper method for implementing a $http request in TypeScript that can be resolved in ui-router?

I have a straightforward HTTP service that I access through a service; module shared { export interface IAuthService { isAuthenticated: () => any; } export class AuthService implements IAuthService { static $inject = [&apo ...

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

Issue encountered on server using next.js - FetchError: failed to process request for https://jsonkeeper.com/b/4G1G

Struggling to fetch JSON data from a link and destructure it for use on the website. I have a getStaticProps export function that extracts the data and I want to pass it into my default Home function to iterate through it. I have come across information ab ...