Error encountered when attempting to dynamically alter property values of an object using Typescript

Can anyone help me figure out how to dynamically change object property values based on the property type in Typescript? I want to replace all string properties with "***", but I keep running into an error that says

Type '"***"' is not assignable to type 'T[keyof T]'

I've searched through the Typescript GitHub repository for a solution, but so far, I haven't had any luck.

As of writing this, I'm using the latest version of Typescript which is "3.8.2".

If you know the correct way to change object property values dynamically, especially when accessing properties like this, please share your insights!

Here's an example code snippet:

interface IClassA {
    name: string;
    age: number;
}

const user: IClassA = {
    name: "Jhon Doe",
    age: 20
};

obfuscate(user);

export function obfuscate<T extends IClassA>(obj: T) {
    for (const prop of Reflect.ownKeys(obj) as (keyof T)[]) {
        if (typeof obj[prop] === "string") {
            obj[prop] = "***";
        }
    }
}

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

Answer №1

I'm not sure why, but a simple (albeit somewhat dirty) trick to achieve this is by converting your text to type any:

if (typeof obj[prop] === "string") {
            obj[prop] = ("***" as any);
}

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

Accessing JSON data from an external file using AngularJS's $http method

I am new to Angular and not very comfortable with JavaScript. I am attempting to create an app using the Ionic framework. I have successfully retrieved a list from a JSON file stored in a variable, but now I am trying to use $http.get() to fetch it from a ...

What is the reason behind VueJS animations only functioning in a single direction?

I'm completely baffled by this issue. It seems that Vue3 is able to apply the move animation class correctly for a <transition-group/> when there is a list of items, but this only happens if the list is moved forward. I've created a CodePen ...

What is the best way to save input values into a Database?

Hey there, I'm a beginner looking to figure out how to send a post request from this input to the database. Can someone guide me on what steps I need to take to make this happen? import { useState, useEffect } from "react"; import axios from ...

What could be causing the issue with my dynamic sitemap.xml file not functioning properly?

I have encountered an issue with creating a dynamic sitemap in my Next.js app. Despite following the instructions in the Next.js documentation and placing a sitemap.js file inside my app directory, I am seeing a 404 error when trying to access http://local ...

Inaccurate ray tracing using an orthographic camera in three.js

Currently working on a 2D CAD drawing viewer using the three.js library. I need the ability to click on objects within the scene to perform operations. However, when utilizing an orthographic camera, I've noticed that the precision of the three.js ra ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

Exploring ways to access an element's background color through JavaScript

Is there a way to access an element's CSS properties that are set by a class name in JavaScript? In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's b ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Learn how to customize button styles in ExtJS with the pressedCls configuration option

Is there a way to change the color when a button is pressed? I tried using the pressedCls config but it didn't work. How can I fix this issue or is there another method to set the CSS when a button is pressed? Thank you so much! Javascript: Ext.crea ...

Utilizing Arrays in Typescript within the Angular Framework

I have developed a Rest API that provides data to populate two drop-down lists in a form. The information retrieved from the API is grabbed by the Angular backend and assigned to the respective drop-downs. Rather than making separate Get requests for each ...

Is it possible to control the functionality of the back button?

Is there a way to customize the behavior of the back button in a browser? For instance, instead of navigating back to the previous page (A.aspx) when a user is on B.aspx, can we make it go to Home.aspx? Is it possible to achieve this using ASP, C#, JavaSc ...

If the camera position in Three.js is trapped within an if-else statement

I am working on enhancing the variability of camera positions in order to make the 3D scene more captivating. However, I am facing an issue where the camera gets stuck at -12, causing it to oscillate between 12.00 and 12.05 before finally moving beyond t ...

What's the best way to implement asynchronous state updating in React and Redux?

In my React incremental-style game, I have a setInterval function set up in App.ts: useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(lo ...

Obtain the position and text string of the highlighted text

I am currently involved in a project using angular 5. The user will be able to select (highlight) text within a specific container, and I am attempting to retrieve the position of the selected text as well as the actual string itself. I want to display a s ...

Basic game of tic tac toe using JavaScript and jQuery

Teaching myself the ropes of JavaScript/jQuery, I decided to dive into building a simple tic tac toe game. Following this example as a guide, I embarked on creating my own version. While most parts seem to be working smoothly, there's one problem that ...

Sending a three.js object as a parameter in JavaScript

I am currently working on a project where I am creating a robot object using javascript and Three.js. I am encountering an issue where the scene object is not being passed into the function, preventing the robot parts from being drawn. Can anyone provide ...

What could be the reason for data-id coming back as undefined?

I'm having trouble figuring out why the code below isn't working for me. The console is showing 'undefined' for data-id. href='#detailsModal' class='btn btn-info btn-xs' data-toggle='modal' data-id='x ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

Vue 3 gracefully handles errors by displaying an alternative component

I am currently developing a rendering library for my Vue 3 + Vite project. Essentially, I have a JSON array of products which I pass to a special <Render :products /> component. This Render component reads all the JSON products and converts them in ...