Is it possible to deduce a generic type from another generic type in TypeScript?

One of the functions I am working with is useFormState(), which requires an object initialValues of type FormType as a parameter.

type FormType = {
    email: string;
    password: string;
    rememberMe: boolean;
}

...

const initialValues: FormType = {
    email: '',
    password: '',
    rememberMe: false,
}

const { values, touched, errors, updateField } = useFormState<FormType, keyof FormType>(initialValues);

The function useFormState() is expected to return an object with keys from the FormType:

touched: {
    email: true,
    password: false,
    rememberMe: false
}

To achieve this typing, I need to extract the "keys" type internally by passing it as the second generic type keyof FormType.

This leads to my question - Is there a way to only pass the type FormType and internally extract the keys type?

The function is defined as follows:

const useFormer = <T, K extends keyof T>(props) => {
  ...
}

Although I could let TypeScript infer the types by omitting them, it becomes confusing when additional properties are added using T.

  • TS can misinterpret the types, and I want users of the function to be certain that what they pass matches the specified Type, hence preferring a single generic type.

It seems like the second type argument K extends keyof T could be completely inferred, but TypeScript requires it if only one type argument is passed.

Is there a way to work around this and use just one type argument?

Answer №1

function customFunction<T>(input: T): {
  touched: {
    [key in keyof T]?: boolean;
  }
  values: T,
  errors: any[],
  updateField: () => void
} {
  ... // Perform operations on the input values
}

TS Playground

This approach avoids using a generic for the keyof, instead calculating it within the function return type interface.

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 find the beginning and end of the week using Moment.js?

Is there a way to retrieve the date of the first day of the week and the date of the last day of the week using Moment.js? I am looking to fetch the dates from the start of the week until the end of the current week based on the current day in Moment.js. ...

Is there a way to silence TypeScript's complaints about a React rendered value being converted into a Date object?

In my latest project using Next.js, TypeScript, Prisma, and Radix-UI, I'm working with a loan object that has various key-value pairs: { "id": 25, "borrowerName": "Test Borrower 1", "pipelineStage": ...

The form will not appear if there is no data bound to it

Can anyone help me with displaying the form even when the data is empty in my template? <form class="nobottommargin" *ngIf="details" [formGroup]="form" (ngSubmit)="onSubmit(form.value)" name="template-contactform"> <div class="col-sm-12 nopad ...

merging pictures using angular 4

Is there a way in Angular to merge two images together, like combining images 1 and 2 to create image 3 as shown in this demonstration? View the demo image ...

Encountering issue in Angular 14: Unable to assign type 'Date | undefined' to type 'string | number | Date' parameter

I have been working on an Angular 14 project where I am implementing a Search Filter Pipe. Below is the code snippet I am using: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'transferFilter' }) export class Trans ...

Icon for closing Mui Snackbar

I am facing an issue with my notification component that uses the mui snackbar to display alerts. I want to display multiple notifications stacked vertically, but when I try to close one notification using the "Close" icon, it ends up closing both that o ...

Finding the IP address of a server in Angular: A Comprehensive Guide

Is there a way to dynamically retrieve the server host IP address in an Angular application launched with ng serve --host 0.0.0.0? This IP address will be necessary for communication with the backend server. As each coworker has their own unique IP addres ...

Displaying a random element from the state array in React Native

I'm attempting to display a random item from the state array, with the possibility of it changing each time the page reloads. Here's what I have tried so far, any suggestions or ideas are welcome! This is my current state: state = { randomIt ...

What are the steps to implement a Bottom Navigation bar in iOS and a Top Navigation bar in Android using NativeScript Angular?

For my project, I decided to utilize the tns-template-tab-navigation-ng template. I am currently working on creating a WhatsApp clone, and in iOS, it features a bottom navigation bar while in Android, it has a top navigation bar. I am looking for guidance ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

How can the value of a number in Angular be changed without altering its original value?

Imagine having the initial number 100. If I enter 50 in another input, it should add 50 to 100. However, if I then change the value from 50 to 80, the total should be 180 and not 230. The goal is always to add numbers to the original sum, not the new valu ...

Can you please explain how I can retrieve information from a Firebase collection using the NextJs API, Firebase Firestore, axios, and TypeScript?

I'm currently utilizing api routes within NextJS 13 to retrieve data from Firebase. The code for this can be found in api/locations.tsx: import { db } from "../../firebase"; import { collection, getDocs } from "firebase/firestore"; ...

Typescript enhances Solid JS by using the "as" prop and the "component" prop

Hey there, I've been experimenting with solid-js lately and I'm facing a challenge integrating it with typescript. My objective is to make my styling more modular by incorporating it within my components. type RelevantTags = Exclude<keyof ...

"Encountering a Vue error while attempting to register the Can component globally with CASL +

I have successfully created a vue + typescript application using vue-cli. I followed the instructions from https://stalniy.github.io/casl/v4/en/package/casl-vue and added the following code: // main.ts import Vue from 'vue'; import App from &apo ...

Creating an Array of Callbacks in TypeScript

How do you define an array of callback functions in TypeScript? Here's how a single callback function looks like: var callback:(param:string)=>void = function(param:string) {}; To declare an array of callbacks, you might try this: var callback: ...

Utilizing Typescript to retrieve a specific object property using square brackets and a variable

How can we correctly access a JavaScript object in TypeScript using variable evaluation with bracket notation, such as myObject[myVariable], when the value of the variable is unknown initially? In the code below, an error occurs due to the uncertainty of ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

Troubleshooting the ReferenceError: Blob is not defined problem with the heic2any library in a Next.js application

Currently, I am encountering an issue where everything is properly implemented and functioning smoothly. However, the main problem arises when I attempt to reload the page, as it results in an error message: ReferenceError: Blob is not defined. This issue ...

The "isActive" value does not share any properties with the type 'Properties<string | number, string & {}>'. This issue was encountered while using React with TypeScript

I'm attempting to include the isActive parameter inside NavLink of react-router-dom version 5, but I'm encountering two errors. The type '({ isActive }: { isActive: any; }) => { color: string; background: string; }' does not have an ...

Converting a string to a number in an Angular template

Within my select box, I am capturing the selected value and binding it to the variable startingYear. However, I need the type of startingYear to be a number, but it is currently registering as a string. Is there a way to convert it to a number? console ...