How can you determine the type of an argument based on the type of another argument?

Is it possible to dynamically assign value types in the

const set = (key: keyof Store, value: any)
function based on the keys defined in the Store interface? For instance, setting a key foo as type number and key bar as type string[].

import store from "electron-store"

interface Store {
  foo: number
  bar: string[]
}

const schema = {
  foo: {
    type: "number",
  },
  bar: {
    type: "array",
    items: {
      type: "string",
    },
  },
} as const

const config = new store<Store>({
  schema: schema,
})

const set = (key: keyof Store, value: any) => {
  return config.set(key, value)
}

Answer №1

Enhancing your style and making set more adaptable:

function setKey<K extends keyof T, T = Storage>(key: K, value: T[K]): void {
  // Logic goes here
}

setKey('username', 'john_doe');
setKey('age', 25);

Alternatively:

const setKey = <Key extends keyof Storage>(key: Key, value: Storage[Key]): void => {
  // Add your functionality
}

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

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

Develop customizable enumerations for use in expandable interfaces

Situation: My objective is to devise a strategy for building scalable state machines in TypeScript using the TypeState library. TypeState offers a typesafe state machine for Typescript, which while not directly related to my current issue, serves as a good ...

What is the process for assigning a predefined type that has already been declared in the @types/node package?

Is there a way to replace the any type with NetworkInterfaceInfo[] type in this code snippet? Unfortunately, I am unable to import @types/node because of an issue mentioned here: How to fix "@types/node/index.d.ts is not a module"? Here is the o ...

Karma Unit test: Issue with accessing the 'length' property of an undefined value has been encountered

While running karma unit tests, I encountered a similar issue and here is what I found: One of my unit tests was writing data to a json file, resulting in the following error: ERROR in TypeError: Cannot read property 'length' of undefined a ...

Angular 7 - ALERT: Circular dependency identified:

Suddenly, a lightbulb went off in my head. I encountered two warnings while running ng serve: WARNING in Circular dependency detected: src\app\_services\ignore-interceptor.service.ts -> src\app\_services\index.ts -> sr ...

Choosing a personalized component using document selector

Currently, I am working on an application using Stenciljs and have created a custom element like this: <custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert> The challenge arises when attem ...

Angular 2: The *ngFor directive is unable to locate a suitable differing framework

Below is the code for client.service.ts clients: Client[]; getClientList() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token&apo ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Troubleshooting Typescript and Redux: Implicitly assigning an 'any' type to the binding element 'string'

Within my React Native app designed for Android, I've integrated a component that relies on the Redux library. Referencing "Hemant" from this thread, it was advised to pass the action as an imported prop into the component. However, I'm encounte ...

The element 'fontFamily' is not recognized within the 'ThemeOptions' type in MUI theming

I'm diving into the world of React and MUI by building my own dashboard from scratch. Let's take a look at my App.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; i ...

What could be causing the issue with my React Native app's release version not opening on a physical Android device?

I encountered an issue while trying to install the Release version of my application. In order to test both the debug and release versions on my physical and virtual devices, I utilized the following commands: ./gradlew assembleDebug, ./gradlew assembleRel ...

Experiencing difficulties with a click event function for displaying or hiding content

Struggling with implementing an onClick function for my two dynamically created components. Currently, when I click on any index in the first component, all content is displayed. What I want is to show only the corresponding index in the second component ...

The use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Tips for disentangling code from types in Typescript

Instead of intertwining code and types like the example below: const compar8 : boolean | error = (action: string, n: number) => { switch(action) { case 'greater': return n > 8; case 'less': ...

What is the best way to leverage TypeScript for destructuring from a sophisticated type structure?

Let's consider a scenario where I have a React functional component that I want to implement using props that are destructured for consistency with other components. The component in question is a checkbox that serves two roles based on the amount of ...

Dividing points in half at the top and bottom edges in a chart using chartjs

https://i.sstatic.net/AfosF.png Upon observation of the provided image, it can be seen that the points are halved when they reach the top or bottom edges, specifically when the data points are 1 or 5 in this context. Various attempts were made to address ...

What are some recommended strategies for incorporating nested routes with separate pages in a React application?

In my React (TypeScript) project, I have a basic routing setup. There's a constant display of a Header and a Footer, a home component for the frontpage, and a Projects section for showcasing past projects worked on. However, I'm facing an issue w ...

Encountered Typescript issue when utilizing typed forms in Angular

Below is the interface I am working with: export interface ILoginDto { email: string; password: string; } Here is a snippet of the relevant code from the component: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; export ...

Failing to retrieve the file instance upon completing the upload process to cloudinary using nestjs

I am attempting to retrieve the secure file URL provided by Cloudinary after successfully uploading the asset to their servers. Although I can upload the file to Cloudinary, when I try to view the response using console.log(res), I unfortunately receive &a ...