Discovering properties based on their types

My dilemma involves an interface set up as follows:

interface A {
   a: string;
}

interface B {
   b: string;
}

export interface C {
   rnd: A;
   rnd2: B;
}

I am seeking a function like update<T>(setting: T) which can identify the property of type T within an object that implements interface C, and then update the value of that property (if it already exists) with the passed setting.

Is there a method to accomplish this task? I attempted iterating and using typeof, but encountered the error message:

This condition will always return 'false' since types 'T' and 'string' has no overlap

Answer №1

To solve this issue, one approach is to provide the key name as a parameter. This way, the compiler can verify that the key name belongs to C and that the value parameter matches the type specified by the key in C:

interface A { a: string; }

interface B { b: string; }

export interface C { rnd: A; rnd2: B;}

let allSettings: C = {} as C
function update<K extends keyof C>(key: K, setting: C[K]) {
    allSettings[key]  = setting;
}

update("rnd", { a: "" }) // valid
update("rnd", { b: "" }) // invalid
update("rnd3", { b: "" }) // invalid 

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

Angular Toaster Notification - There are currently no toaster containers set up to display notifications

Currently, I am utilizing the angular2-toaster library within my Angular application. It is quite straightforward - you simply define a toaster container in the template of your component: <toaster-container></toaster-container> Then, you ca ...

A step-by-step guide on incorporating MarkerClusterer into a google-map-react component

I am looking to integrate MarkerClusterer into my Google Map using a library or component. Here is a snippet of my current code. Can anyone provide guidance on how I can achieve this with the google-map-react library? Thank you. const handleApiLoaded = ({ ...

Utilizing string literals as index signatures

I've created a code snippet called MyTest that maps over an object: type MyTest<T> = { [P in keyof T]: T[P]; }; type Result = MyTest<{hello: 'world', foo: 2}>; // ^? type Result = { hello: 'world', foo: 2 } ...

How to utilize the async pipe on an observable<Object> and connect it to a local variable in the HTML using Angular

Hey there! So, I have this observable called user$ which has a bunch of properties such as name, title, and address. component{ user$:Observable<User>; constructor(private userService:UserService){ this.user$ = this.userService.someMethodRet ...

The parameter 'prev: todoType[] => todoType[]' cannot be assigned to the type 'todoType[]'.ts(2345)

An issue has arisen with this.props.update as mentioned in the title import { useState } from "react"; import axios from "axios"; import { todoType } from "../../types/todo"; type sendResponse = { task: string; }; type getRe ...

Form a fixed array category based on an object class

I have a structure similar to the following: type Fields = { countryCode: string; currency: string; otherFields: string; }; Additionally, I possess an immutable array that looks like this: // Type: readonly ["countryCode", "currency", "otherFields"] ...

Increase the ngClass attribute's value

Is there a way to automatically increment a numeric value in a class using the ngClass directive? For example, can we achieve something like this: <some-element [ngClass]="'class-*'">...</some-element>, where the asterisk (*) will in ...

The React hook useState is struggling to accurately map array objects

Recently, I encountered an issue with a form that sends an array of objects to another React Functional Component: import React, { useState } from 'react' import uuid from 'uuid/v1'; const NewMovieForm = ( {addMovie }) => ...

The content security policy is preventing a connection to the signalr hub

Currently, I am developing an application using electron that incorporates React and Typescript. One of the features I am integrating is a SignalR hub for chat functionality. However, when attempting to connect to my SignalR server, I encounter the followi ...

When a Vue3/Vuex object created using reactive() is used as a payload in a mutation to Vuex, it loses its reactivity

Ever wondered why you might need a reactive object compatible with Provide/Inject for your Vuex Store? Well, it's all about flexibility and functionality! Picture this: you have a plugin for authentication that needs to be integrated into your app. B ...

Accessing variables outside an Angular 2 component

On one of my pages, I am using a component like this: <ion-navbar *navbar class="contact_navbar"> <ion-title>About us</ion-title> </ion-navbar> <ion-content> <ck-about [channel]="ionic" [template]="template_1"> ...

Create a checklist with unique identification, value, and description by utilizing an array of objects

Utilizing React with Typescript, I am tasked with constructing the React component MultiSelectCheckBoxes by supplying an array of Objects of type Color to the constructor: The structure for a checkbox list should be like this: const options = [{ "id": ...

Angular 2 - resolving the access control allow origin header issue

My project utilizes Spring on the back-end and Angular2 on the front-end. In the webapp folder of my Spring project, there is a JSON file that I am attempting to access from Angular. I can successfully access the file by directly typing "http://localhost: ...

how can I retrieve an array of nested objects from two interrelated tables that have a one-to-many relationship using

Hey everyone, I have a scenario where I'm working with 2 MySQL tables: itemsClass which holds various classes, and itemType which links to itemClass and contains type values for a specific class. My goal is to create a service that returns an Observa ...

What is the best method to integrate an external SDK using Java files in a React Native project while still maintaining a clean code

I am working on a React Native CLI project for an Android app and I need to integrate a Java SDK to access certain functions. The problem is that the SDK frequently updates, so I don't want to modify the original Java code directly (and can't use ...

Unusual problem arises when working with exclusions and inclusions in tsconfig.json

I've encountered a peculiar issue. When I specify the following in my configuration: "exclude": [ "node_modules", "**/__tests__", "**/*.test.*", "**/server-handlers/**/*", "**/ ...

What steps do I need to take to deploy an Angular 4, instead of Angular 2, application on IIS

Despite numerous attempts, I struggled to run a simple "Hello world" application in Angular 4 on IIS. All my efforts resulted in a blank page with no errors. The only successful methods I found were: 1- Building the application using the "ng build" CLI ...

The Firebase function for updating the counter is experiencing delays

My real-time database has a counter variable that increments with each function call. However, if multiple users trigger the function simultaneously when the counter is at 1, they both get the same value for the counter (1) instead of it incrementing to 3 ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

ts-jest should replace the character '@' with the '/src' folder in the map configuration

I have set up a node project using TypeScript and configured various paths in my tsconfig.json file, such as: "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl' ...