The process of exporting a singleton instance

I have created a new class called AppViewModel with a setting property set to 1:

class AppViewModel {
  setting: number = 1;
}

export = AppViewModel;

Afterward, I imported the class and instantiated it within another class named OrderEntry:

import AppViewModel = require("appViewModel");

class OrderEntry {
    appViewModel = new AppViewModel();
    doTest() {
        alert(this.appViewModel.setting);
}

}

The code functions correctly. However, I wish to change it to a singleton pattern. So, I updated the export statement as follows:

export var instance  = new AppViewModel();

Subsequently, I made a slight adjustment in the consuming class:

import AppViewModel = require("appViewModel");

class OrderEntry {
     appViewModel = AppViewModel;
     doTest() {
         alert(this.appViewModel.setting); //Error Here
  }
}

Unfortunately, upon compilation, an error was raised stating that:

Property setting does not exist on type.

How can I resolve this issue?

Answer №1

Here's a solution that worked for me:

let newInstance = new AppViewModel();
module.exports = newInstance;

Initially, Visual Studio was displaying the type as Any instead of AppViewModel. After making the above change, it recognized it correctly as an instance of AppViewModel.

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

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

Issue found in the file assert.d.ts located in the node_modules directory: Expected '{' or ';' at line 3, character 68. Error code: TS1144

When attempting to start the angular application with ng serve, I encountered an error. Below are the project details: Angular CLI: 8.2.0 Node: 14.19.1 OS: darwin x64 Angular: 8.2.0 ... animations, cli, common, compiler, compiler-cli, core, forms ... platf ...

Strategies for setting the output value for a defined generic type

Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in? type Diff<T, U> = T extends U ? never : T type DiffTypes<T, U> = ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Utilizing Azure Function Model v4: Establishing a Connection with Express.js

Using Model v4 in my Azure function index.ts import { app } from "@azure/functions"; import azureFunctionHandler from "azure-aws-serverless-express"; import expressApp from "../../app"; app.http("httpTrigger1", { methods: ["GET"], route: "api/{*segme ...

What is the proper way to type the SubmitEvent so that the event.target.children property can be accessed

Below is the form I currently have: <form id="search" method="post"> <input type="text" name="query" id="search-field"/> </form> I am looking to add a submit event listener in TypeScript: ...

Is it Mission Impossible to Combine NodeJs, Restify, SQL Server, TypeScript, and IIS?

Starting a Rest API project using NodeJS with Restify on a Windows environment (local server with IIS and SQLServer) while also using Typescript may seem like a difficult task. Is it an impossible mission? Does anyone have any helpful guides, documentatio ...

Integrate Angular 2 components into WebStorm

I am currently working on a project using Angular 2 (rc5) and TypeScript (1.8.10). Angular 2 is built with TypeScript, but in the node_modules directory, I notice that there are JavaScript files (*.js) along with declaration files (*.d.ts). It makes it di ...

Utilize mapGetter and mapMutations in Vuex with TypeScript without the need for class-style components syntax

After completing a project in Vue, I found myself getting a bit confused without static types. To address this, I decided to incorporate TypeScript into my project while still maintaining the traditional way of writing code, without classes and decorators. ...

The 'jsx' property in tsconfig.json being overridden by Next.js and TypeScript

Is there a way to prevent NextJS from changing the 'jsx' property in my tsconfig.json file from 'react' to 'preserve' when running the development server? This is how my tsconfig.json file looks: "compilerOptions": { " ...

Unit testing with Jest in TypeScript for mocking Express and Mongoose

I've been struggling to find comprehensive resources on using jest.fn() to mock TypeScript classes and their methods, like express' Request, Response, NextFunction, and the save() method on a mongoose model. For instance, suppose I have the foll ...

Utilizing Angular 2 to retrieve and assign object properties provided by a service to a local variable within a

My video service: public getExercise(exerciseId): Observable<Exercise[]>{ let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers, withCredentials: t ...

Challenges in designing components in Angular 2.0 and beyond

Issue at hand - There are two input controls on the same page, each belonging to separate components. When a value is entered into the first input box, it calculates the square value and updates the second input control accordingly. Conversely, if the v ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Web application is not making API calls

Currently, I am experimenting with calling data from an API to create a simple weather application for practice purposes. I have been using the inspect element feature in my Chrome browser to check if the console will show the data log, but unfortunately, ...

Establish a connection between two JSON files using the WordPress REST API

I have developed an app using ionic 2 that revolves around quotes. My goal is to manage these quotes (along with authors, categories, etc) using Wordpress and its REST API. Initially, I utilized normal posts for this purpose, but now I am exploring custom ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

Utilizing TypeScript to Populate an observableArray in KnockoutJS

Is there a way to populate an observableArray in KnockoutJS using TypeScript? My ViewModel is defined as a class. In the absence of TypeScript, I would typically load the data using $.getJSON(); and then map it accordingly. function ViewModel() { var ...

What is the syntax for assigning a public variable within a TypeScript function?

I am finding it challenging to assign a value to a public variable within another function. I seem to be stuck. export class MyClass{ myVar = false; myFunction(){ Module.anotherFunction(){ this.myVar = true; } } } ...