Value-driven parametric typing

Currently working on developing a custom form type. Here's what I have so far:

function getCustomType<Values extends Record<string, unknown> = Record<string, unknown>>({
  defaultValue,
  onSubmit
}: {
  defaultValue: Values
  onSubmit: (values: Values) => void
}): {
  value: Values
  onSubmit: (value: Values) => void
} {
  return {
    value: defaultValue,
    onSubmit
  }
}

const formData = getCustomType({
  defaultValue: { dog: 1 },
  onSubmit: (data) => { 
    alert(1)
  }
})

Seeking to let the value in the onSubmit function correspond with the data from the defaultValue object without needing an additional function call. Is this achievable through a more straightforward approach?

Answer №1

When defining the interface like this:

interface Ciccio <T extends Record<string, unknown> = Record<string, unknown>> {
  value: T
  onSubmit( value: T ): void
}

You can utilize the interface to automatically assign types in the onSubmit function when creating a new object:

const newCiccio: Ciccio <{ cand: number }> = {
  value: { cand: 1 },
  onSubmit: function( arg ) {
    // The argument 'arg' is typed here
  }
}

It's important to note that specifying the type when defining a new value is crucial if you want a more specific type than the default Record<string, unknown>. If you need the type in the onSubmit function to be inferred without explicitly providing it as a type argument when declaring the interface (i.e., replacing Ciccio <{ cand: number }> with just Ciccio), it seems not possible without using a function as in your original approach.

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

Encountering a type error with gatsby-plugin-dark-mode in a Typescript Gatsby setup

Issue with Layout warning in index.tsx when hovering: (alias) const Layout: ({ children }: Props) => JSX.Element import Layout Type '{ children: Element[]; }' is missing the following properties from type 'Props': theme, >toggle ...

Can we use type mapping and conditional types to make it mandatory for an object to have certain specified keys?

Someone sent over a type definition from a 3rd party library: interface UpdateRequest { data?: ValueRange[]; options?: Options } I am trying to implement a method with the following signature: update(params: RequiredOnly<UpdateRequest, 'dat ...

Display the chosen HTML template in real-time

Recently, I started using Angular 2 and encountered an issue that I need help with. 1] I have created 2-3 templates for emails and SMS that will display predefined data. 2] I have also designed a screen with a dropdown menu containing options like email ...

Creating an Object with Quoted Key in JavaScript/Typescript for MongoDB's '$push' Feature

Struggling to format the data in order to add an element into a nested array within MongoDB. Currently attempting this in TypeScript: var data = {$push:{"foo.12.bar":{ prop1: prop1, prop2: prop2, // referenced values above this code snippet ...

Typescript's confidential variables

Currently, I am delving into the world of Angular2 and familiarizing myself with working with classes in javascript for the first time. I'm curious about the significance of using the private parameter in the constructor, as opposed to simply writing ...

Exploring the functionality of the Angular 7 date pipe in a more dynamic approach by incorporating it within a template literal using backticks, specifically

I have a value called changes.lastUpdatedTime.currentValue which is set to 1540460704884. I am looking to format this value using a pipe for date formatting. For example, I want to achieve something like this: {{lastUpdatedTime | date:'short'}} ...

Using Jasmine and ReSharper to test TypeScript modules

In my VS2017 project, I have a Jasmine test written in TypeScript: describe("A simple test", () => { it("Should succeed", () => { expect(true).toBeTruthy(); }); }); Everything runs smoothly using the ReSharper test runner. However, when I ...

What is the best way to extract a specific property from an object?

Consider the following function: getNewColor(): {} { return colors.red; } Along with this object: colors: any = { red: {primary: '#ad2121',secondary: '#FAE3E3'}, blue: {primary: '#1e90ff',secondary: '#D1E8FF&apos ...

I'm puzzled as to why TypeScript isn't flagging any typing errors in this code

Take a look at this code snippet showcasing two extended classes: interface payloadCollection { [key: string]: payloadObject<object, object> } type payloadObject<TExpectedData extends object = {}, TExpectedResponse extends object = {}> = ...

Issue encountered while testing a component that incorporates a templateUrl

Upon reviewing the test output, it appears that console.log(dummyComponentInstance); is being invoked and resulting in undefined. In addition, the log for console.log('beforeEach done'); is never displayed. The code within dummy.component.spec. ...

Oops! Encounterred a TypeError stating "Unable to access properties of an undefined object" while working with react native

Within my React Native Quiz function, I have implemented a fetch GET request to load data. Upon checking if the data has loaded using the showQuestion variable, I encounter an error message: Cannot read properties of undefined (evaluating 'questObj[ ...

Tips on how to efficiently yield a resolving Promise Like object from a for loop

In my custom function, I have a promise-like object that decrypts a given message using the web crypto API. The issue is that in my decryption function, I need to test several different values as input and run this promise-like object multiple times in a f ...

What's the best way to determine the type of the enum literally?

I am working with an enum called RadCheck that looks like this: enum RadCheck { blank = 0, userDefined = 1, macAddress = 2, } const H = RadCheck[RadCheck.blank] Currently, the variable H is being recognized as a string, but I want it to be inferred ...

Angular NX: Managing multiple libraries with identical names

Currently integrating Angular with NX, I have established two distinct groups: books and cars. My goal is to develop an overview library for each group that includes a table for viewing either books or cars. To start, I created the library under libs/book ...

Working with Union Types in the state of React's Context API using TypeScript

I'm facing an issue where TypeScript is not recognizing the existence of the property state.recipes when I use the state in another component. This seems to occur when YummlyState is the type of RecipesState. I have a hunch that YummlyState always def ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

Route protection is ineffective when dealing with two observables simultaneously

After writing the route guard as shown below, I encountered an issue with the else statement that was not returning a result, even though it should have. Surprisingly, there were no errors either. this.hotelSettingsService.get().pipe(map(res => { ...

The variable in my NodeJS code is persisting across multiple requests and not being reset as expected

After setting up a project with the help of Typescript-Node-Starter, I have successfully created a controller and a route to call a specific function. import { Request, Response } from "express"; import axios from "axios"; import { pars ...

What is the most effective method for waiting for multiple requests to complete?

I am working on a component that requires fetching data from multiple endpoints through independent API calls. I want to make all these calls simultaneously and only load the user interface once all the data has been fetched successfully. My approach invo ...

Best method for defining an object in JSON in Typescript

I am working on an Angular 2 application and have a JSON object that I need to declare in typescript correctly. Here is the structure of the object: data = [ { 'id':1, 'title':'something' 'node': [ ...