Setting a value to an optional property of an inherited type is a simple task that can

export interface CgiConfiguration {
    name: string,
    value?: string
}
export interface CgiConfigurationsMap {
   [configurationName: string]: CgiConfiguration
}
const createCGI = <T extends CgiConfigurationsMap>(configurations: T) => configurations
const CGI = createCGI({
    bindCardPreCheck: {
        name: ''
    }
})

CGI.bindCardPreCheck.value = 'xxx'

Check out a TypeScript demo here

CGI.bindCardPreCheck.b = 'xxx' this line results in an error:

Property 'b' does not exist on type '{ a: string; }'.

How can we address this issue?

Answer №1

The issue arises with the current implementation of createCGI. It validates the compatibility between T and CgiConfigMap, but then it returns the exact type of the object literal passed in, which may not include the property b. You have the option to directly return CgiConfigMap, but you will lose the specific property names from the object literal.

An improved approach would be to return a mapped type that retains the properties from the first level of the object literal while assigning all these properties the type of CgiConfig.

export interface CgiConfig {
    a: string,
    b?: string
}
export interface CgiConfigMap {
    [cgiName: string]: CgiConfig
}
const createCGI = <T extends CgiConfigMap>(cgi: T) : { [P in keyof T]: CgiConfig } => cgi
const CGI = createCGI({
    bindCardPreCheck: {
        a: ''
    }
})

CGI.bindCardPreCheck.b = 'xxx' //now works as expected

Answer №2

let CGIInstance = initializeCGI<CgiConfigMap>({
  bindCardPreCheck: {
    item: ''
  }
})

alternatively

let CGIInstance = initializeCGI({
  bindCardPreCheck: {
    item: ''
  }
} as CgiConfigMap)

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

fakeAsync failing to synchronize with async task completion

Scenario In my testing process, I am evaluating a component that utilizes an observable-based service to retrieve and display data for internationalization purposes. The i18n service is custom-made to cater to specific requirements. While the component ...

What is the correct way to construct this query?

I've been attempting to run this query with Sequelize but keep encountering an error Query LineItem.findAll( { attributes: [ "orderId", [fn("sum", col("quantity")), &qu ...

Navigate to the login page in Angular 2

Initially, the template login (login.component) needs to be called first. Once the login is complete, then app.component will be loaded. Is it possible to achieve this? And if so, how can I do it? Edited Question: I am already using CanActivate. Apologi ...

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

Is there a way in Typescript to filter for the first instance of a unique object in an array of objects?

Having an array of JSON objects like this, the task is to iterate through it and retrieve the first occurrence of 'appname', such as 'app1' or 'app2', and store the entire object for each... myArray[ { ...

Navigating through a JSON dictionary in Svelte: A step-by-step guide

When working with Svelte, the #each construct allows for easy iteration over array-like objects. But what if you have a JSON dictionary object instead? Is there a way in Svelte to iterate over this type of object in order to populate a dropdown menu? The ...

Next.js (TypeScript) - Error: Property 'req' is not recognized on the type 'GetServerSideProps'

Currently, I am tackling a challenge involving the utilization of next-auth and attempting to access the session from within getServerSideProps. However, in order to achieve this, it is essential for me to provide the context request and context response ...

Error encountered when attempting to export a TypeScript class from an AngularJS module

In my application using Angular and TypeScript, I have encountered a scenario where I want to inherit a class from one module into another file: generics.ts: module app.generics{ export class BaseClass{ someMethod(): void{ alert(" ...

Distributing a library of components using Vite, Vue 3, and Typescript to npm

My current challenge involves publishing a Vue 3 component library with Vite, all written in Typescript. The issue I'm facing is that the type definitions are not being included in the package when imported into another project. Upon importing the co ...

How to disable the onChange event in PrimeNG p-dropdown?

I'm currently utilizing PrimeNG's dropdown component. Each option in the list includes an icon that, when clicked, should trigger a specific method. Additionally, I need to execute another method when the onChange event of the dropdown is trigger ...

Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue: <button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked" Description: A total of 10 buttons are displayed on the screen. When I click on button number 1, each button receives the clas ...

Image paths becoming unresponsive following package upgrades

My Angular2 application was originally built using angular-cli (v 1.0.0) and webpack2. Within a component, I had the ability to reference an image like so: <div class="country-flag"> <img [src]="src/assets/flags/32/jp.png" [width]="flagIconSiz ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

How can we leverage mapped types in TypeScript to eliminate properties and promisify methods?

Below is the provided code snippet: class A { x = 0; y = 0; visible = false; render() { return 1; } } type RemoveProperties<T> = { readonly [P in keyof T]: T[P] extends Function ? T[P] : never//; }; type JustMethodKe ...

Is it feasible to set an empty object as the initial default value in the state of a React component?

In my React application with TypeScript, I am using "react": "^17.0.0". Here is how I define the app state: export interface IRoleState { data: API.RoleItem, menus: API.MenuItem, } When I set up the initial state like this: con ...

Can you provide instructions on how to use RXJS Observables to conduct a service poll?

If I want the get request to "api/foobar" to repeat every 500 milliseconds, how can I modify the code provided below? import {Observable} from "RxJS/Rx"; import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; @Injectable() export ...

Is it possible to update input form fields in an Angular application?

I am currently designing a straightforward web page featuring a modal for creating a new object named Partner and sending it to the server. The page also includes multiple input fields to showcase the newly created data. In this project, I am utilizing Ang ...

A Model in TypeScript

{ "title": { "de-DE": "German", "fr-FR": "French", "en-CA": "English" }, "image": "/tile.jpg", "url": "/url/to/version" } After receiving this JSON data, my model structure is as follows: export class MyModelStruct ...

Error encountered: Unable to locate React Node during FaC testing with Jest and Enzyme

In my React Native app, we recently integrated TypeScript and I'm in charge of migrating the unit tests. One particular test is failing unexpectedly. The app includes a <LoginForm /> component that utilizes Formik. //... imports export inte ...

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...