Using Typescript to establish the dependency of one parameter's type on another parameter

Let's imagine a scenario where

interface Action<T> {
    assignAction(key: keyof T, value: any): void;
}

The type T is defined as

{
    users: User[];
    accounts: Account[];
}

Now, when using the assignAction method, if we attempt to pass in accounts for the key of users, it will result in an error due to mismatched types:

assignAction('users', accounts)

Determining how to validate the value parameter becomes challenging as its type depends on the chosen key.

Answer №1

To clarify the relationship, you can enhance the assignAction function by adding a generic.

interface Action<T> {
    assignAction<K extends keyof T>(key: K, value: T[K]): void;
}

By specifying a generic type for your Action instance, it will be able to establish the link between key and value when invoking assignAction.

Answer №2

interface TypeA {
    objectIdentifierA: string
}

interface TypeB {
    objectIdentifierB: string
}

interface TypeC {
    objectIdentifierC: string
}

enum Category1 {
    OptionA = "OptionA",
    OptionsBC = "OptionsBC"
}



type NamespaceKeyDirectory =
    & Record<Category1.OptionA, TypeA>
    & Record<Category1.OptionsBC, TypeB | TypeC>;

type NamespaceKeys<T extends Category1.OptionA | Category1.OptionsBC> = NamespaceKeyDirectory[T];

function evaluate<NS extends Category1, Key extends NamespaceKeys<NS>>(section: NS, key: Key) {
    console.log("Invoked");
}

const itemA = {
    objectIdentifierA: "test"
} as TypeA;

const itemB = {
    objectIdentifierB: "test"
} as TypeB;

const itemC = {
    objectIdentifierC: "test"
} as TypeC;

evaluate(Category1.OptionA, itemB) // not permissible
evaluate(Category1.OptionA, itemA)
evaluate(Category1.OptionsBC, itemA) // not permissible
evaluate(Category1.OptionsBC, itemB)
evaluate(Category1.OptionsBC, itemC)

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

What is the best way to transfer global Meteor variables to templates and effectively utilize them?

I am in the process of developing a compact, single-page application game that emulates the dynamics of the stock market. The price and behavior variables are influenced by various factors; however, at its core, there exists a finite set of universal varia ...

Utilizing ReactJS to retrieve configuration settings from a YAML file, similar to how it is done

Our team is currently using a full-stack multi-microservice application where the backend java components utilize the spring @value annotation to fetch configuration values from a yml file. This method has been effective and even the Java side of our UI c ...

Error: The CommentsSection function did not return any values after rendering

I've been working on a project to create a simple web page that features multiple Material UI card components and integrates Redux to simulate a basic social media platform. The main issue I'm encountering is that when I try to expand a card, an ...

The prop type `cellHeight` provided to `GridList` in (Material-ui / React) is invalid

warning.js:33 Warning: The prop type for cellHeight in the GridList component is invalid. I encountered this error message, despite the property functioning correctly. Is there a way to resolve this issue? If you're interested, check out the documen ...

"Utilizing the 'await' keyword within a JavaScript 'for of'

Could there be an issue with my code? I am utilizing express and mongoose router.get('/c/:hashtoken', validateEmailToken, catchAsync(async(req,res)=>{ const hashtoken = req.params.hashtoken const hashtoken2 = createHash('sha256&ap ...

Steps for retrieving the image URL after clicking on an image within a list of images

I have a list of images in the index file shown below: <div id="image-list" <ul> <li data-id='1'> <img src='image/001.jpg' alt=''> </li> <li data- ...

Updating the input value in a React application

With a list and an edit button, upon clicking the edit button, a new modal opens. How can I auto-populate the selected username email? The server-side response is {this.test.name}, where I provide him with the input value to auto-populate. However, when ...

Server Error: Experiencing an overload of renders. React has set limits on the number of renders to avoid getting caught in an endless loop

I am currently attempting to develop a basic stopwatch application and encountering the following error message. Despite trying various solutions from similar queries, I have not been able to pinpoint the root cause of this issue or resolve it. Below is t ...

Which HTML element does each script correspond to?

Are there any methods to identify the script used in certain HTML elements? For instance, if I wish to determine the script responsible for creating a drop-down menu, I can locate the HTML and CSS for the menu but not the JavaScript (or other scripts). I ...

What could be the reason for this JavaScript malfunctioning in both Chrome and Safari browsers?

Why is it that the javascript works fine in Firefox for the gallery on the page below, but doesn't seem to be functioning properly in Chrome and Safari? In Chrome, the big image isn't displaying but the thumbnails are, and in Safari nothing show ...

Execute action based on local state when component is unmounted in React

I have encountered an issue with a component's internal state not being properly propagated throughout the application, specifically under certain events. const FunComponent = (initialDescription, onSave) => { const [description, setDescription] ...

Transform Image on Hover in ReactJS

I am working on a Card Component that includes an image and text. Initially, the image is redImage and the text is black. When hovering over the card, I want the redimage to change to whiteimage and the text color to change to white as well. The content ...

Trouble with setInterval not refreshing the HTML element

I'm currently working on a script that should update the value of an element every second. However, I've encountered an issue where the element only updates the first time and then stops. Strangely, there are no errors appearing in the console ei ...

What is the best way to divide middleware within feathers?

I have been using the multer library with feathers to upload files. In my effort to separate logic from code, I have decided to move the upload functionality from the index.js file to a new file named pdf.js within the middleware directory. Below is the c ...

Obtain a listing of values that appear multiple times within an array

I need a solution to find values that appear more than once in an array. The current code I have is quite complex. var arr = [1, 2, 3, 4, 2, 3]; var flag = {} var exist2arr = []; for(var i = 0; i < arr.length; i++){ for(var j = 0 ; j < arr.leng ...

Unlocking the Potential of NextJS with Dynamic Page Export - Say Goodbye to Static HTML!

I am attempting to export my NextJs project based on the official documentation provided. However, it seems that I can only export it into static HTML. Is there a way to export it into dynamic pages where user-submitted data is updated in real time, simil ...

How to replace the xth occurrence with jQuery or JavaScript

Looking for a solution to update a specific character in a string like the following scenario: var str = "A A A A A"; The goal is to replace a particular 'A' with another value. For example, replacing the 3rd 'A' with some ...

Unable to capture Metamask Errors

I am attempting to invoke a smart contract using ethers.contract and the signer from ethers.providers.web3Provider to leverage MetaMask. If the transaction fails, I want to capture the error and either retry or invoke a different function. However, my proj ...

Keep the final item in an array that shares the same attribute

I am working with an array const obj=[{fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"}, {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093 ...

Using TypeScript to convert a JSON date string into a Date object

The backend is sending me a JSON data structure that resembles the following: [{ "schedulingId": "7d98a02b-e14f-43e4-a8c9-6763ba6a5e76", "schedulingDateTime": "2019-12-28T14:00:00", "registrationDateTime": "2019-12-24T16:47:34", "doctorVie ...