Exploring the World of Typescript Interfaces

I have an interface defined in my code that looks like this.

interface MyFlag {
   flag1: boolean,
   flag2: boolean
}

In my code, I initialize the interface like this.

let myFlag: MyFlag = {"flag1":true, "flag2": true};
let dummy = myFlag;
console.log("dummy: " + JSON.stringify(dummy));
myFlag = {"flag1": false, "flag2": false};
console.log("dummy2 : " + JSON.stringify(dummy));

After running these lines of code, here are the logged results:

dummy: {"flag1":true, "flag2": true};
dummy2 : {"flag1":false, "flag2": false}; 

The confusion arises from the fact that the value of "dummy" appears to change when I modify myFlag.

My question is, "Is there a way to keep 'dummy' as its initial assigned value?" It seems likely that this behavior is related to the nature of interfaces.

Any assistance on this matter would be greatly appreciated.

Thank you and regards,

SD

Answer №1

I'm puzzled by the fact that "dummy" changes value when I modify myFlag.

dummy shouldn't change when a new object is assigned to myFlag, but it should change when the internal state of myFlag is altered.

Below is the JavaScript-transpiled version of your code. In this snippet, you assign a new object to myFlag, yet the value of dummy remains unaffected (which contradicts what you reported).

var myFlag = {
    "flag1": true,
    "flag2": true
};

var dummy = myFlag;
console.log("dummy: " + JSON.stringify(dummy));

myFlag = { "flag1": false, "flag2": false };
console.log("dummy2 : " + JSON.stringify(dummy));

// dummy: {"flag1":true,"flag2":true}
// dummy2 : {"flag1":true,"flag2":true}

You're likely encountering the distinction between 1. altering the state of the object that a variable references and 2. modifying the value of the reference within a variable. Here's an example to illustrate:

let foo = {
    value: "first"
};

// at this point, foo and bar hold references to the same object
let bar = foo;

console.log(foo.value + " " + bar.value); // first first

// here, we are changing the internal state of that object
// both variables change
foo.value = "second";
console.log(foo.value + " " + bar.value); // second second

// here, we are changing the value of the reference in foo
// now, foo and bar refer to different objects 
foo = {
    value: "third"
};

console.log(foo.value + " " + bar.value); // third second

// here, we are changing the internal state of the object referenced by bar
// this doesn't impact the object referenced by foo
bar.value = "fourth";
console.log(foo.value + " " + bar.value); // third fourth

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 effectively utilizing the 'or' operator when working with disparate data types

One of my functions requires an argument that can have one of two different types. If you're interested in TypeScript functions and types, take a look at the official documentation, as well as these Stack Overflow questions: Question 1 and Question 2 ...

I am struggling to understand the significance of the $ symbol in this particular context

I came across the following snippet in a book I've been reading: `images/${Date.now()}.jpg` The curly brackets used here signify 'out of string', but I'm unsure about the meaning of $... P.S. Honestly, I didn't want to ask a que ...

Having trouble importing or resolving files with ts-loader or css-loader?

Struggling to incorporate css modules by utilizing style-loader and css-loader in my project. I am facing difficulties understanding the root cause, unsure if it's ts-loader or css-loader to blame. webpack.config.js const path = require('path&a ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

Integrating a non-nullable static type into memoized components leads to a lint error - refer to the example provided for

Example 1: When defining a non-nullable someStaticProperty, a lint error will be thrown: import { NamedExoticComponent, memo } from "react"; type WithComponentId = { componentId: string }; type ScreenComponentStaticMembers = { someStaticProperty: str ...

Import Information into Popup Window

When a user clicks on the "view" button, only the details of the corresponding challenge should be displayed: Currently, clicking on the "view" button loads all the challenges. This is because in my view-one-challenge.component.html, I have coded it as fo ...

Fetching data from React Router v6 Navigate

When I navigate to a new route, I am encountering an issue with passing state data in TypeScript. The error message says: Property 'email' does not exist on type 'State'." The parent functional component looks like this: naviga ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Ensuring that an object containing optional values meets the condition of having at least one property using Zod validation

When using the Zod library in TypeScript to validate an object with optional properties, it is essential for me to ensure that the object contains at least one property. My goal is to validate the object's structure and confirm that it adheres to a sp ...

Although everything appears to be running smoothly in Express, my request is returning null

I am facing an issue with a router in my code. In the main index.ts file, I have the following line: app.use("/api/tshirts", tshirts) And in tshirts.ts file, I have defined the following routes: router.get("/", tshirtsController.getTShirts) router.get("/ ...

In TypeScript, what is the return Type of sequelize.define()?

After hearing great things about TypeScript and its benefits of static typing, I decided to give it a try. I wanted to test it out by creating a simple web API with sequelize, but I'm struggling to understand the types returned from sequelize. Here ar ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

I am unable to transmit information using the `http.post` function

When attempting to send a post request to the backend, I am receiving a response code of 500 and an empty data object on the API side. Interestingly, using Postman gives successful results. return http.post(link,data,headers).subscribe(response=>{ ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Selected structures in rust

Can a struct be selected in a way that the type checker can handle without any issues? Coming from TypeScript: // Assuming a main object type with all fields: interface User { id: number; name: string; password: string; }; // Using a picked t ...

Overlap with upper picture formatting

I've been struggling to create an ion-card with two images: a main picture and a small book cover. Any ideas on how to achieve this? Note: The layout should have 2 images, one at the top and another as a small book cover. Check out this sample on St ...

The utilization of a Typescript Generic for basic addition is not producing the desired results

This issue feels incredibly insignificant, but for some reason I can't seem to figure out why it's not functioning correctly. It seems like the return type should match since I am simply concatenating or adding based on whether it's a number ...

Tips for reducing a discriminated union by using the key value of a Record

I am working with a union type that has a discriminator property called "type". I then define a Record<> where the keys are the "type" property values. How can I specify the second generic parameter of the Record (Record< , this param>) so tha ...

Error: TypeScript React Google Maps: The object 'google' is not recognized

After successfully loading the Google Maps JavaScript API in the public/index.html, I can log window.google.maps without any issues in the dev tools console. https://i.sstatic.net/XqeG5.png However, TypeScript seems unaware of its presence, resulting in ...

What is the best way for me to examine [...more] closely?

import * as Joi from 'joi'; import 'joi-extract-type'; const schema = { aaaaaaa: Joi.number() .integer() .positive() .allow(null), bbbbbb: Joi.number() .integer() .positive() .all ...