What is the best way to access the type of a generic property within a type?

type Mother = {
    action<X>(alpha: X, bravo: string):void
}
type ChildArguments = Parameters<Mother['action']<number>> // encountered an issue

Assuming the aforementioned code is functioning properly, I will be able to execute the following:

const childArguments: ChildArguments = [1, '1']

Answer №1

If you're searching for a way to manipulate types at a higher level, the type system won't provide a direct solution automatically.

However, if you're willing to tolerate a slight runtime impact, along with some complex type manipulation, and you're using TypeScript 3.4 or later, you can achieve your desired type like this:

const dummyParams =
    ((x => () => x) as <A extends any[]>(
        f: (...args: A) => any) => () => A
    )(null! as Parent['fun'])<number>();
type ChildFunArgs = typeof dummyParams
// type ChildFunArgs = [number, string]

You can confirm that the type of ChildFunArgs is as expected. The runtime behavior of the emitted code is essentially:

const dummyParams = ((x => () => x))(null)();

which is equivalent to:

const dummyParams = null;

So, while there is a runtime impact, it is minimal.


How does this intricate process work? Essentially, we trick the compiler by creating a hypothetical function:

declare function params<A extends any[]>(f: (...args: A)=>any): () => A;

This function, if it existed, would take a function argument f and return a new function that yields a tuple matching the parameter types of f. While impossible to actually implement, we don't need to.

We then simulate having a value of the type of the fun method of Parent:

 declare const parentFun: Parent['fun'];

Next, we call params on it:

const paramsParentFun = params(parentFun);
// const paramsParentFun: <T>() => [T, string]

Thanks to recent improvements in higher-order function handling, the compiler infers the type of paramsParentFun as <T>() => [T, string]. Now, you can simulate calling this function and manually specifying number as T:

const dummyParams = paramsParentFun<number>();
// const dummyParams: [number, string]

And there you have it! You've achieved your desired outcome.

The condensed code utilizes type assertions to deceive the compiler about the existence of other functions and values, resulting in cleaner emitted JavaScript code.

I hope this explanation clarifies things for you. Best of luck!

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

Preserve the timestamp of when the radio query was chosen

I'm interested in finding a way to save the user's selected answer for a radio button question and track the time they saved it. Is there a way to achieve this using HTML alone? Or would I need to utilize another coding language or package? Just ...

Challenges surrounding asynchronous functionality in React hooks

I've been facing some issues with this code and have resorted to debugging it using console.log(). However, the results I'm getting are not making any sense. Can someone help me identify what's wrong with this code? I noticed that my console ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

What is the method to incorporate a fresh generic parameter without officially announcing it?

My goal is to define a type union where one of the types extends an existing type: // The original type type Foo<V> = { value: V; onChange: (value: V) => void }; // Type union incorporating Foo type ADT = ({ kind: "foo" } & Foo<a ...

Attention Needed - Certain vulnerabilities necessitate manual review for resolution

npm audit === Security Report from npm audit === # You have 1 vulnerability that can be resolved by running `npm update terser-webpack-plugin --depth 3` Severity Issue ...

Issue: React cannot render Objects as children (received: [object Promise]). If you intended to display multiple children, please use an array instead. (Next)

My dilemma is this: I am trying to display my GitHub repositories on a React component, but I keep encountering the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, u ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Google's reCAPTCHA issue: systemjs not found

Currently, I am attempting to integrate Google's reCAPTCHA into an Angular application by following a helpful tutorial found here. However, I have encountered a problem as the systemjs.config.js file seems to be missing from my Angular CLI project. An ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...

Special scenarios requiring OnPush Change Detection

I'm currently building an Angular 2 application using ngrx, and I've been intrigued by the concept of OnPush change detection for optimizing performance. After reading multiple articles on the topic, it seems that the general consensus is: "If a ...

Can anyone provide a solution for fixing TypeScript/React error code TS7053?

I encountered an error message with code TS7053 which states: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; isLandlocked: boolean; }'. No index signa ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

RC6 - What is the significance of encountering an 'Unexpected token <' error message?

After updating to RC.6, I am encountering a series of errors related to third-party components. Specifically, the error message displayed is: SyntaxError: Unexpected token <. This issue has arisen with ng2-bootstrap, ng2-select, and angular2-jwt. Howev ...

Avoid using propTypes for props verification

Looking for a solution to handle multiple props on a button: interface buttonProps { secondary?: boolean; tertiary?: boolean; width?: number; children?: any; icon?: string; } If the button includes an icon without any children, how can ...

Discovering the process of iterating through values from multiple arrays of objects and applying them to a new response in Angular 8

Received the following data from an API response: const apiResponse = { "factoryId": "A_0421", "loss": [ { "lossType": "Planned Stoppage Time", "duration": ...

Authentication of users using NextJS Dashboard App API

I am currently following this tutorial, but instead of fetching data via a PostgreSQL request, I want to utilize an API. When I call an async function with await, it initially returns undefined and then the user object after receiving a response from the ...

WebStorm's TypeScript definitions are failing to function properly

I'm experiencing an issue with my three.js code and TypeScript definitions in settings. Despite enabling them, there doesn't seem to be any effect. I've downloaded everything and checked the necessary boxes, but nothing is changing. WebStorm ...

How to disable typescript eslint notifications in the terminal for .js and .jsx files within a create-react-app project using VS Code

I'm currently in the process of transitioning from JavaScript to TypeScript within my create-react-app project. I am facing an issue where new ESLint TypeScript warnings are being flagged for my old .js and .jsx files, which is something I want to avo ...