using a property key as a generic argument when passing in TypeScript

Check out this Codesandbox link to see some code:

type Tags = "TAG1" | "TAG2";

export type S<Tag extends Tags> = {
  tag: Tag;
  get<K, R>(k: K): R;
};

const store = {
  one: "ONE"
};

type Keys = keyof typeof store;

const s: S<"TAG1"> = {
  tag: "TAG1",
  get<K extends Keys>(k: K) {
    return store[k];
  }
};

An error occurs with the line:

get<K extends Keys>(k: K) {

The types are incompatible: Type '<K extends "one">(k: K) => { one: string; }[K]' is not assignable to type '<K, R>(k: K) => R'. Types of parameters 'k' and 'k' are incompatible. Type 'K' is not assignable to type '"one"'.ts(2322

Is it possible to pass a key value like this using TypeScript?

Answer №1

Avoid using a generic as the return type

type Tags = "TAG1" | "TAG2";

export type S<Tag extends Tags> = {
  tag: Tag;
  get<K extends Keys>(k: K): Store[K];
};

const store = {
  one: "ONE"
};

type Store = typeof store
type Keys = keyof typeof store;

const s: S<"TAG1"> = {
  tag: "TAG1",
    get<K extends Keys>(k: K):Store[K] {
      return store[k];
    }
  };

const x = s.get('one') // string

Playground

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

Deactivate Search Functionality for Users who are not Logged in on an Angular 2 Application

The login component and view are functioning as intended, preventing users from accessing AuthGuard protected routes if they're not logged in. However, I'm facing a challenge with the search bar displayed on the home login screen (actually presen ...

Attempting to create a bar graph using Angular framework

I'm currently working on developing a dashboard in Angular that includes a chart feature. Within my Firebase Firestore database, I have two collections: 'mechanicQualifications' and 'mecanicos'. The 'mechanicQualifications&apo ...

Angular5 causing all divs to have click events at once instead of individually triggered

I am a beginner when it comes to working with Angular and I have encountered an issue. I created a click event on a FAQ page in Angular 5, but the problem is that when I click on one FAQ, they all open up instead of just the targeted one. Here is my TypeS ...

What is the best way to manage a promise in Jest?

I am encountering an issue at this particular section of my code. The error message reads: Received promise resolved instead of rejected. I'm uncertain about how to address this problem, could someone provide assistance? it("should not create a m ...

Issues encountered while developing a ReactJS application using TypeScript

While attempting to create a React app using the command npx create-react-app client-app --use-npm --typescript, I expected to generate a project with TypeScript files, but instead ended up with index.js and app.js rather than index.tsx and app.tsx. Could ...

What is the best way to update this payload object?

Currently, I'm developing a route and aiming to establish a generic normalizer that can be utilized before storing user data in the database. This is the function for normalization: import { INormalizer, IPayloadIndexer } from "../../interfaces/ ...

Resolving typescript error in my custom hook

Implementing this ResizeObserver hook in my project using typescript const useResizeObserver = () => { const [entry, setEntry] = useState<ResizeObserverEntry>(); const [node, setNode] = useState<Element | null>(null); const observer = ...

Developing a node module that includes nested subfolders

I'm currently working on an npm module and have the following index.ts file: export * from './src/A/index'; Right now, when importing in my app, it looks like this: import {something} from 'myModule'; Now, I want to enhance my ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

Next.js: Importing from a new endpoint triggers the code execution once more

Here is a simplified example I created for this specific question. Imagine I want to maintain a server-side state. components/dummy.ts console.log('initialize array') let number: number = 0 const incrementValue: () => number = () => numbe ...

Is there a way to convert my messages into different languages without relying on the 'translate' directive or pipe?

Currently, my Angular application is set up with ngx-translate for translation purposes. While it is currently monolingual, I am already looking ahead to the possibility of needing to translate it in the future. Everything is functioning perfectly, but I w ...

Struggling with rotating an image in React

Currently I'm troubleshooting an issue with the rotate button on my React-Avatar Editor. The functionality is not working as intended. For reference, here is a link to the code: https://codesandbox.io/s/example-for-react-avatar-editor-ofoz4 ...

The TypeScript import statement is causing a conflict with the local declaration of 'Snackbar'

I'm having trouble using the Snackbar component from Material UI in my React app that is written in TypeScript. Whenever I try to import the component, I encounter an error message saying: Import declaration conflicts with local declaration of &apos ...

Customizing MUI V5 Variants

I'm having trouble customizing the variant options in MUIPaper, and I can't figure out what mistake I'm making. The available types for the component are: variant?: OverridableStringUnion<'elevation' | 'outlined', Pape ...

JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays? The structure of my array is as follows: tabs=[ {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: ...

This error message in Typescript occurs when the compiler is unable to locate the specified function name, causing

I have incorporated typings and made references to them. I am uncertain about the correctness of the typings as I am not well-versed in writing them. However, this is what I have done: // This is where I encounter an error stating 'Cannot find name & ...

Using Angular services without specifying a specific type

Currently, I have a component that needs to make an API request. In addition, there exists an abstract class designed for handling such services with the following constructor: export class ODataService<T> extends ApiService { constructor(http: Htt ...

Error TS2345: The argument provided, which is of type 'Promise<ReadonlyArray<Object>>', cannot be assigned to a parameter that must be of type 'T | PromiseLike<T> | undefined'

My goal is to return the ReadonlyArray<> in my promise so that I can send it back to the original method that called 'dispatchToThisProcess'. This abstraction allows for potential future updates to multiple processes. Below is the code snip ...

Can we deduce the value of a Record datatype in TypeScript?

Is it possible to have TypeScript infer the type of statusColor as yellow instead of Color? type Status = 'Invalid' | 'Progress' | 'Complete' | 'Error'; type Color= 'yellow' | 'red' | 'gree ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...