Separate the generic function interface into its own type/interface variable

Below is an example of TypeScript generics that I found on typescriptlang.

function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
  return obj[key];
}

let x = { a: 1, b: 2, c: 3, d: 4 };

getProperty(x, "a");
getProperty(x, "m");

I wanted to extract the generic type to a variable for reuse. However, my attempt resulted in an error:

type MyType<Type, Key extends keyof Type> = {obj: Type, key: Key}

let x = { a: 1, b: 2, c: 3, d: 4 };


function getPropertyGeneric(params: MyType<x>) {
  return obj[key];
}

The error message reads:

Generic type 'MyType' requires 2 type argument(s).

Playground

Answer №1

When defining the following type:

type MyType<Type, Key extends keyof Type> = {obj: Type, key: Key}

You are required to explicitly provide 2 type parameters like so:

function getPropertyGeneric(params: MyType<typeof x, keyof typeof x>) {
  return params.obj[params.key];
}

Link to playground

However, you can utilize generic parameter default for the second type parameter by defining MyType as:

type MyType<Type, Key extends keyof Type = keyof Type> = {obj: Type, key: Key}

This allows you to either provide or omit the second type parameter:

function getPropertyGeneric2(params: MyType<typeof x, keyof typeof x>) { // no error
  return params.obj[params.key];
}

function getPropertyGeneric1(params: MyType<typeof x>) { // no error
  return params.obj[params.key];
}

Link to playground

It's important to note that using the value x in a type context is not allowed. You must instead retrieve its type using the typeof operator.

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

Enhancing Angular2 Routing with Angular4 UrlSerializer for Seamless HATEOAS Link Integration

As a newcomer to Angular4, I am currently exploring how to consume a HATEOAS API. My goal is to either pass an object that contains the self reference or the self reference link itself through the routing mechanism (for example, by clicking on an edit link ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Challenges in designing components in Angular 2.0 and beyond

Issue at hand - There are two input controls on the same page, each belonging to separate components. When a value is entered into the first input box, it calculates the square value and updates the second input control accordingly. Conversely, if the v ...

Express Server Providers for Angular 17's Server-Side Rendering

I attempted to share my request and response object with the Angular application by defining Providers in the "server.ts" file. However, when injecting them into app.component, they always appear undefined regardless of whether I am in the server or clie ...

Encountering an issue when using the Google authentication provider with Next.js version 13

I am currently working on integrating next-auth with the Google provider and Prisma in my Next.js application, but I encountered the following error: Error: Detected default export in '/MyProject/foodbrain/app/api/auth/[...nextauth]/route.ts'. Pl ...

The issue persists in VSCode where the closing brackets are not being automatically added despite

Recently, I've noticed that my vscode editor is failing to automatically add closing brackets/parenthesis as it should. This issue only started happening recently. I'm curious if anyone else out there has encountered this problem with their globa ...

I'm encountering an issue trying to apply array filtering with checkboxes using React hooks and TypeScript

Help needed! I'm facing an issue while trying to filter an array based on gender using checkboxes. The functionality works fine for the male checkbox but seems to fail when clicking on the female checkbox. Below is the code snippet from my App.tsx fil ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

Using TypeScript to import npm modules that are scoped but do not have the scope name included

We currently have private NPM packages that are stored in npmjs' private repository. Let's say scope name : @scope private package name: private-package When we install this specific NPM package using npm install @scope/private-package It ge ...

Exploring the Augmented Theme in Material UI Using TypeScript and the "keyof" Operator

I've recently started working with TypeScript and I'm facing an issue that I can't seem to solve. Here's the problem: I extended my Material UI theme with the following types: declare module '@material-ui/core/styles/createPalette& ...

I am encountering issues with the TypeScript repository build on my local machine, but it successfully passes when

I am encountering an issue with a TypeScript repository failing to build on my local machine. The error message I receive is as follows: $ tsc --pretty -p tsconfig.json ../../../../../../node_modules/@types/graphql/subscription/subscribe.d.ts:17:12 - erro ...

Migrating image information from Angular version 14 to Asp.Net Core 6.0 Rest Api

When transferring product model data from Angular to a REST API using FormData, there is an images array included in the product data. Upon receiving this product in the REST API, the images data is accessed using Request.Form.Files. The images are then se ...

I'm curious about how to implement textarea functionality within Angular for modeling purposes

I have a desire to utilize the model and transmit it to the server. One instance of this is sending comments. comment.model.ts export interface Comment { article_no: number; username: string; nickname: string; creatat: Date; content: string; } ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...

Data fetched by Next.js is failing to display on the web page

After writing a fetch command, I was able to see the data in the console.log but for some reason it is not showing up in the DOM. export default async function links(){ const res = await fetch('https://randomuser.me/api/'); const data = ...

Retrieve the specific object's methods based on a specified return type criteria

Initially, I have a class containing attributes and methods. My goal is to filter and retrieve only the keys of the methods. I created a utility type for this purpose and it worked smoothly: type FunctionPropertyNames<T> = { [K in keyof T]: T[K] e ...

Tips for resolving the error message "Cannot use type 'string' to index type"

Currently, I am in the process of migrating a website from React to Next.js, and I am facing challenges when it comes to implementing i18n for SSR pages. I am following a tutorial provided at this link: I have already set up a lang folder and placed some ...

loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I ...

Vue3 and Typescript issue: The property '$el' is not recognized on type 'void'. What is the correct way to access every existing tag type in the DOM?

Currently, I am in the process of migrating a Vue2 project to Vue3 and Typescript. While encountering several unusual errors, one particular issue with $el has me puzzled. I have been attempting to target every <g> tag within the provided template, ...

Using TypeScript to set an HTMLElement in a web page

Currently in the process of transitioning my old JavaScript code to TypeScript. One of the components I have is a Table Of Contents JSX component that helps me navigate easily to specific headings. I had a function that calculated the total offset needed ...