Creating a TypeScript object declaration

I am looking for some help with converting this JavaScript code to TypeScript. I am new to both languages, and when trying to access the 'this' object in my TypeScript version, I get an error message saying that 'this possibly be unknown'. Can someone please show me how to implement this code in TypeScript?

const singleton = {

    instance: null, // socket.io instance

    getInstance: (server) => {
        if (!this.instance) {
            this.instance = server; // takes 'Hello' as the value
        }
        return this.instance;
    },

}

let a = singleton.getInstance('Hello');
let b = singleton.getInstance('World');

console.log(a === b); // true
console.log(a); // Hello
console.log(b); // Hello

Answer №1

Give this method a shot:

class UniqueInstance {

    static unique = null; // instance of the class

    static getUniqueValue(value) {
        if (!UniqueInstance.unique) {
            UniqueInstance.unique = value; // assigns 'This is unique' as the value
        }

        return UniqueInstance.unique;
    }

}

let x = UniqueInstance.getUniqueValue('This is unique');
let y = UniqueInstance.getUniqueValue('Different value');

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

Tips for utilizing a received variable within an ejs document

I am currently attempting to update the content of an HTML element in an EJS file with a variable that I have defined in a JavaScript file. let checkbox = document.querySelector('input[name="plan"]'); checkbox.addEventListener('ch ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

Setting up Webpack for Node applications

My current challenge involves configuring Webpack for a node app that already exists. I am encountering various issues and struggling to find solutions or even know where to begin. Situation The project's folder structure is as follows: +---app +-- ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...

Exploring how to alter state in a child component using a function within the parent component in React

class ParentComponent extends Component { state = { isDialogOpen: false, setStyle: false } handleClose = () => { this.setState({ isDialogOpen: false, setStyle: false }) } handleOpen = () => { this.setState({ isDialogOpen: true ...

Creating a diverse layout by dynamically adding divs without achieving uniformity in the grid

I'm working on dynamically generating a grid of divs with a specific size using the code below: function createGrid(gridSize) { var container = document.getElementById('container'); for (var i = 0; i < gridSize; i++) { va ...

Getting the mssql output in Protractor using VSCode

I recently tried running the code below and it seems like the connection is established successfully. However, I'm unable to see any output. Is there a way to view the query result? I am still learning about Protractor, NodeJS, and MSSQL connections. ...

Sliding horizontally with a responsive touch

I am looking to implement a horizontal responsive page navigation, similar to the illustration shown below: This is my current progress: DEMO $(document).ready(function () { var slideNum = $('.page').length, wrapperWidth = 100 * s ...

What is the best way to display div elements based on a selected option?

Here is the code for a select list that contains the number of guests for a room: <select name="txtHotelGuestNO" id="txtHotelGuestNO" class="hotels" onchange="show_room_choose()"> <?php for($i=1;$i<=100;$i++) echo "<option value=$i>$ ...

Delete an <li> element upon clicking a span tag

I've been attempting to fadeOut some <li> elements, however I haven't had any success. Here's my code below: <li class="lclass" id="1"> First Li <span class="removeit" id="1" style="color:#C00;">Remove</span> ...

Retrieve DOM elements within a Vue.js modal using JavaScript

I have integrated the Vue.js modal into my Vue app using a Vue component. The template section of this component includes the modal itself: <template> <!-- Modal: Edit exercise --> <modal name='edit-exercise-modal' ...

What is the recommended approach for conducting backend validation?

As I develop a CRUD application using express.js and node.js, here is the backend API code that I have written: app.post("/signup", (req, res) => { const { name, email, password } = req.body; if (!name) { res.status(401).json("Please provide a n ...

Summing up various results from promises [Protractor]

On my webpage, I have set up two input text boxes and a label. My aim is to extract the numbers from these elements, sum up the numbers in the text boxes, and then compare the total with the number in the label. Does anyone know how I can achieve this? He ...

Jquery Visualization Chart not displaying

I am struggling to get the jquery visualization to work properly. Although the table and caption appear fine, there is no data showing up in the chart. I've carefully followed the example and searched for any issues, but I can't identify what&apo ...

Ensuring the accuracy of input data in all input fields with the help of dojo

1)In my Dojo widget, I have two additional widgets loaded inside. If I need to clear all text boxes within the widget, I currently use this method: this.myAttachPoint.value="". Is there an alternative code that can achieve the same result without adding ...

Uploading Boolean Values from Switch Input (React/Typescript)

I'm facing an issue while trying to post the state value of a switch input toggle control. Whenever I use the submitRecommendation() function through a button click, I encounter a JSON parse error: Cannot deserialize instance of `boolean` out of START ...

While attempting to encrypt a private key in JavaScript using dotenv, I encountered an issue: TypeError - I was unable to read properties of undefined, specifically 'toHexString'

Welcome to encrypt.js const ethers = require("ethers"); const fs = require("fs-extra"); require("dotenv").config(); async function main() { const wallet = new ethers.Wallet(process.env.RRIVATE_KEY); const encryptedJsonKey ...

"Transforming a query into a JSON array - a step-by-step

My query generates the following output: { key:1,label:"R. Bulan"} { key:2,label:"R. Bintang"} { key:3,label:"R. Akasia"} { key:4,label:"R. Guest Room"} This is my SQL query: select '{ '||'key:'||IDMEETINGROOM||''||',l ...

Unable to utilize query parameters with an ExpressJS API on localhost

Within my index.js file app.use('/api/v1/users', userRouter) In the Router file router.get("/:id", getUserDataById); When using Postman: The GET URL I am using is: http://localhost:3000/api/v1/users?id=120622 The error message is: C ...

Updating input value in React on change event

This is the code for my SearchForm.js, where the function handleKeywordsChange is responsible for managing changes in the input field for keywords. import React from 'react'; import ReactDOM from 'react-dom'; class SearchForm extends ...