Ways to deduce function parameters by explicitly defining the object type

Seeking input on improving the title of this code snippet. Here's an example that needs your expertise:

type Query = ((...params: any[]) => Promise<any>);

type Resource = {
  query: Query;
}

export type Params<T> = T extends ((...params: infer R) => Promise<any>) ? R : any[];

const resource: Resource = {
  query: (id: string) => Promise.resolve(id)
}

const inferredResource = {
  query: (id: string) => Promise.resolve(id)
}

type ResourceParams = Params<typeof resource['query']>;
type InferredResourceParams = Params<typeof inferredResource['query']>;

Playground

The challenge lies in ensuring that the object conforms to the shape defined by Resource, while also inferring its parameters for later use.

In the current setup, either the structure is guaranteed but the inference fails, or vice versa. Is there a way to achieve both goals simultaneously?

Answer №1

It's important to note that there is a utility type called Parameters<>, which performs a similar function to your Params, albeit in a slightly different manner.

The issue at hand here stems from a misunderstanding of where the type is being derived from. Despite Query allowing for any Promise-returning function to be assigned, the true type of Resource.query remains as specified by Query - namely, any[].

When the type is inferred, it reflects the actual parameter provided (in this case, a string) since no other information is available. The shape of inferredParams still aligns with Query (as id: string can coexist within ...args: any[]), hence it is treated as conforming to the Query interface.

Therefore, ResourceParams equates to any[], while InferredResourceParams corresponds to id: string.

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 could be causing the 'controls' property to be undefined when using form: FormGroup in an Angular 11 component?

Just diving into Angular 11 and getting to grips with TypeScript.. I'm trying to access the 'controls' property in a specifically defined 'FormGroup' variable. But for some reason, it keeps saying that the property is undefined... ...

The conclusion from utilizing the TypeScript class factory mixin is that it does not yield a constructor function

While attempting to utilize mixin classes in TypeScript, I encountered an issue. The return value of the mixin application (Sizeable.mixin() in the following code) is reported as "not a constructor function". However, it is puzzling because the error outpu ...

Methods for defining a variable in React with Typescript without encountering the "Index signature is missing in type" issue

I am facing an issue while trying to declare a variable 'reports' and assigning it to an array of arrays containing string and number types. The problem arises when I try to assign it, resulting in errors. ... // Retrieving data from an API let ...

The feature of Nuxt 3's tsconfig path seems to be malfunctioning when accessed from the

Take a look at my file structure below -shared --foo.ts -web-ui (nuxt project) --pages --index.vue --index.ts --tsconfig.json This is the tsconfig for my nuxt setup. { // https://v3.nuxtjs.org/concepts/typescript "exte ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

Tips for linking the controls of storybook with manual state updates

I'm a newcomer to storybook and frontend development. Below is the code for my checkbox.tsx component: import React from 'react'; import styles from './checkbox.module.css'; // Make sure this import is correct interface CheckboxP ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

What is the relationship between an object and a class in typescript and how can we define

import type { Scene, Camera } from 'three' interface SceneWithActiveCamera extends Scene { activeCamera: Camera } let scene: SceneWithActiveCamera Is there an alternative method to achieve the same result without using an interface? ...

What causes yarn install to pull in a GitHub repository dependency while npm install does not?

When adding a github repository (specifically TypeScript project) as a dependency in package.json, such as: "ethereumjs-vm": "git+https://github.com/ethereumjs/ethereumjs-vm.git#v4.0.0-beta.1" I am interested in extending some classes from this public pr ...

The Angular NgFor directive can only be used to bind data to Iterables like Arrays

I am encountering an issue when attempting to iterate through and display data using ngFor. The specific error appearing in the console is "Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only su ...

Sorting an array of numbers in TypeScript using the array sort function

Looking to organize an array based on ID, comparing it with another array of numbers var items:[] = [{ item:{id:1},item:{id:2},item:{id:3},item:{id:4} }] var sorted:[] = [1,3,2,4]; Output: var items:[] = [{ item:{id:1},item:{id:3},item: ...

Organizing a vast TypeScript project: Comparing Modules and Namespaces

As someone relatively new to TypeScript, I am currently working on a small prototyping framework for WebGl. During my project refactoring, I encountered challenges in organizing my code, debating between using modules or namespaces as both have their drawb ...

Develop a mapping system using enums that ensures compiler errors are enforced

I am struggling to enforce a mapping on an object in TypeScript. My goal is to define a type or interface that maps from ANIMAL_PLACE to ANIMAL_TYPE. I want the type to ensure that any object created with these mappings includes both the ANIMAL_PLACE and A ...

What could be the reason why my focus and blur event listener is not being activated?

It seems like everything is in order here, but for some reason, the event just won't fire... const element = (this.agGridElm.nativeElement as HTMLElement); element.addEventListener('focus', (focusEvent: FocusEvent) => { element.classLi ...

Setting Max or Min Date to Today for Date Input in Angular 2 and Ionic 2

<input class="alert-input date-input" #dob="ngModel" name="dob" max="2018-03-07" [(ngModel)]="leadDetail.dob" type="date"></div> Is there a way to dynamically set the max date to today instead of 2018-03-07? I have tried a couple of methods b ...

The MemoizedSelector<ICommonAppState, IMenuItemsObject[]> argument does not match the expected 'string' parameter type

I have implemented the use of createSelector from @ngrx/store in order to select an array of objects from my store. Despite successfully compiling my application, I encountered the following error: Argument of type 'MemoizedSelector<ICommonAppSta ...

Steering clear of using relative paths in Angular CLI

I am currently using the most up-to-date Angular CLI and have set up a custom components folder to store all of my components. For instance, within the TextInputComponent, there is a TextInputConfiguration class located in src/components/configurations.ts ...

In order to work with Mongoose and Typescript, it is necessary for me to

I am currently following the guidelines outlined in the Mongoose documentation to incorporate TypeScript support into my project: https://mongoosejs.com/docs/typescript.html. Within the documentation, there is an example provided as follows: import { Sche ...

Geolocation plugin in Ionic encountered an issue: "Geolocation provider not found"

I've been working on implementing geolocation in my ionic2 hello world project, and I successfully added the ionic plugin called "Geolocation" by following the instructions on the official website. After running these two commands: $ ionic plugin add ...

Deliberately choosing not to fulfill the Bluebird Promise

Here is a piece of code that needs to call a callback which may return a promise. The goal is to resolve the promise and log an error if it fails, without the caller knowing about it or waiting for the promise to fulfill. However, not returning the promise ...