Setting up Typescript: The Guide to Declaring a Dependent Property

In my current project, I am working on creating a declaration file for the quadstore library. This library has a class that requires a constructor parameter called contextKey. The value of this parameter determines the name of a field on method arguments. To put it simply, in Typescript terms, it would look something like this:

interface MethodArg {
  a: string;
  b: string;
  <<The property name here depends on the value of contextKey>>: string;
}

class A {
  constructor(options?: {contextKey: string}) {}

  fn(arg: MethodArg) {...}
}

I am currently exploring how to declare the type of MethodArg so that its third property's name is dependent on the value provided to the class constructor. Is it even possible to achieve this in a declaration file?

Answer №1

It may not be feasible because the value of the constructor parameter is determined at runtime, while the type of MethodArg is set during compile time(?), making it impossible for the latter to rely on the former. However, if you wish to convert the value into a type parameter (thus providing runtime information to compile time), you could try implementing it in the following manner:

type MethodArg<E extends keyof any> = {
  [T in E]: string;
} & { a: string; b: string };

class A<T extends string> {
  constructor(options?: { contextKey: T }) {}
  fn(arg: MethodArg<T>) {}
}

new A({ contextKey: "foo" }).fn({
  a: "100",
  b: "100",
  foo: "foo",
});


// Avoid doing it this way
let foo: string = "123";
new A({ contextKey: foo }).fn({
  a: "100",
  b: "200",
});

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

Creating a unique object by dynamically incorporating features from another object

I've recently implemented a tree structure in my UI using Material Tree, and it requires creating a new object to represent the tree. The initial object format is as follows: [ { name: 'Fruit', children: [ {name: 'Apple& ...

Redirecting to login on browser refresh in Angular using Firebase's canActivate feature

An Angular 5 authentication application using angularfire2 and Firebase has been developed. The app functions correctly when navigating through in-app links. However, an issue arises when refreshing the browser, as it redirects back to the Login page even ...

The expiration of the Gitlab CI/CD cache leads to the failure of the build process

I have an AWS CDK application in TypeScript and a simple GitLab CI/CD pipeline with 2 stages for deployment: image: node:latest stages: - dependencies - deploy dependencies: stage: dependencies only: refs: - master changes: - ...

Is there a method to enhance the efficiency of generating the code coverage report in VSTS?

What are the possible reasons for the extended duration (>1 min) required to generate the code coverage report when running the associated command in VSTS? Are there any strategies that can be implemented to streamline this process? ...

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...

The response parser in Angular 7 is failing to function correctly

Hey, I recently updated my Angular from version 4.4 to the latest 7 and after encountering several errors, I was able to get my service up and running. However, I'm facing an issue with my output parser function which is supposed to parse the login re ...

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

Angular 2 Validation Customizer

Recently, I created a web API function that takes a username input from a text field and checks if it is already taken. The server response returns Y if the username is available and N if it's not. For validating the username, I implemented a Validat ...

Incorporate Select2 functionality within the Angular2 application

I'm currently working on incorporating the Select2 plugin into my Angular2 application. Successfully, I have managed to set up select2 and transform my multiple select fields as expected. However, I am now facing a challenge in retrieving the selected ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Show Timing on the Y-Axis - Bubble Graph

Recently, I stumbled upon the Bubble Chart feature in ng2-charts. I am trying to display data based on time on the Y-axis and values on the X-axis. My dataset consists of x:[10,35,60], y:["7.00 AM"], with r having the same value as x. However, the sample d ...

TypeScript integrated Cypress code coverage plugin

I've been attempting to integrate the @cypress/code-coverage plugin with TypeScript in my project, but so far I haven't had any success. Here is a breakdown of the steps I've taken thus far: Followed all the instructions outlined in https:/ ...

The specified data type is not compatible with the current context and cannot be treated as an array

Just starting out with TypeScript and I've encountered an issue that's preventing me from successfully building my app. Everything runs smoothly on my local environment, but as soon as I try to build it, an error pops up. Here's a snippet o ...

Specify the second parameter as a generic class that corresponds to the first parameter of the function

Given the example below, the second parameter of the fn function requires a class with a static attribute controle and an instance attribute controle, both of type number. interface Base { controle: number new(...args: any[]): { controle: n ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

Rearranging items within an array in a React component

Currently, I am facing a situation where I have created a list that dynamically adds a React Node upon clicking a button. The final layout of the model looks like this: https://i.sstatic.net/fG37r.png Here is the code snippet for your reference: import ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...

Best practice for validating a form using React: Why the state doesn't update immediately with useState and onSubmit

I'm currently working on implementing a custom form validation for my React project using Typescript. However, I've encountered an issue with the useState hook not updating the state containing errors immediately upon form submission. Let me illu ...

Unable to interact with Span in a table cell - Protractor/Typescript error

I am facing an issue where clicking on the Span Element within a Grid cell is not working. I have tried using actions and the code below, but neither worked for me. Any advice would be greatly appreciated. async SaveorCancelRow() { var table = this. ...

I am unable to refresh the table data in Angular

Here is the code that I am currently working with: I am facing an issue where my webpage is not updating its data after performing delete or any other operations. The user list is not being displayed in the data. Despite my attempts, I have been unable to ...