How can we leverage mapped types in TypeScript to eliminate properties and promisify methods?

Below is the provided code snippet:

class A {
    x = 0;
    y = 0;
    visible = false;
    render() {
        return 1;
    }
}

type RemoveProperties<T> = {
    readonly [P in keyof T]: T[P] extends Function ? T[P] : never//;
};

type JustMethodKeys<T> = ({ [P in keyof T]: T[P] extends Function ? P : never })[keyof T];
type JustMethods<T> = Pick<T, JustMethodKeys<T>>

type IsValidArg<T> = T extends object ? keyof T extends never ? false : true : true;

type Promisified<T extends Function> =
    T extends (...args: any[]) => Promise<any> ? T : (
        T extends (a: infer A, b: infer B, c: infer C, d: infer D, e: infer E, f: infer F, g: infer G, h: infer H, i: infer I, j: infer J) => infer R ? (
            IsValidArg<J> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J) => Promise<R> :
            IsValidArg<I> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I) => Promise<R> :
            IsValidArg<H> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H) => Promise<R> :
            IsValidArg<G> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => Promise<R> :
            IsValidArg<F> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F) => Promise<R> :
            IsValidArg<E> extends true ? (a: A, b: B, c: C, d: D, e: E) => Promise<R> :
            IsValidArg<D> extends true ? (a: A, b: B, c: C, d: D) => Promise<R> :
            IsValidArg<C> extends true ? (a: A, b: B, c: C) => Promise<R> :
            IsValidArg<B> extends true ? (a: A, b: B) => Promise<R> :
            IsValidArg<A> extends true ? (a: A) => Promise<R> :
            () => Promise<R>
        ) : never
    );

var a = new A() as JustMethods<A>  // I want to JustMethod && Promisified
a.visible // error
var b = a.render() // b should be Promise<number>

How can this be implemented? The goal is to remove the 'visible' property and promisify the 'render' method. How can we combine Promisified and JustMethods for this purpose?

Answer №1

To properly implement the desired functionality, it is necessary to utilize a mapped type that specifically targets the methods of the designated type by leveraging JustMethodKeys and applying Promisified to each property.

class A {
    x = 0;
    y = 0;
    visible = false;
    render() {
        return 1;
    }
}

type JustMethodKeys<T> = ({ [P in keyof T]: T[P] extends Function ? P : never })[keyof T];

type IsValidArg<T> = T extends object ? keyof T extends never ? false : true : true;

type Promisified<T extends Function> =
    T extends (...args: any[]) => Promise<any> ? T : (
        T extends (a: infer A, b: infer B, c: infer C, d: infer D, e: infer E, f: infer F, g: infer G, h: infer H, i: infer I, j: infer J) => infer R ? (
            IsValidArg<J> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J) => Promise<R> :
            IsValidArg<I> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I) => Promise<R> :
            IsValidArg<H> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H) => Promise<R> :
            IsValidArg<G> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => Promise<R> :
            IsValidArg<F> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F) => Promise<R> :
            IsValidArg<E> extends true ? (a: A, b: B, c: C, d: D, e: E) => Promise<R> :
            IsValidArg<D> extends true ? (a: A, b: B, c: C, d: D) => Promise<R> :
            IsValidArg<C> extends true ? (a: A, b: B, c: C) => Promise<R> :
            IsValidArg<B> extends true ? (a: A, b: B) => Promise<R> :
            IsValidArg<A> extends true ? (a: A) => Promise<R> :
            () => Promise<R>
        ) : never
    );

type PromisifyMethods<T> = { 
    // We take just the method key and Promisify them, 
    // We have to use T[P] & Function because the compiler will not realize T[P] will always be a function
    [P in JustMethodKeys<T>] : Promisified<T[P] & Function>
}

//Usage
declare var a : PromisifyMethods<A>  
a.visible // error
var b = a.render() // b is Promise<number>

Edit

Following the initial response, TypeScript has evolved with a more concise solution to the problem at hand. With the introduction of Tuples in rest parameters and spread expressions, there is no longer a need for multiple overloads within Promisified:

type JustMethodKeys<T> = ({ [P in keyof T]: T[P] extends Function ? P : never })[keyof T];


type ArgumentTypes<T> = T extends (... args: infer U ) => any ? U: never;
type Promisified<T> = T extends (...args: any[])=> infer R ? (...a: ArgumentTypes<T>) => Promise<R> : never;

type PromisifyMethods<T> = { 
    // We take just the method key and Promisify them, 
    // We have to use T[P] & Function because the compiler will not realize T[P] will always be a function
    [P in JustMethodKeys<T>] : Promisified<T[P]>
}

//Usage
declare var a : PromisifyMethods<A>  
a.visible // error
var b = a.render("") // b is Promise<number> , render is render: (k: string) => Promise<number>

This updated approach not only simplifies the process but also addresses various issues:

  • Optional parameters remain optional
  • Argument names are retained
  • Works seamlessly with any number of arguments

Answer №2

Here is a different take on the code snippet provided:

type Method = (...args: any) => any;
type KeysOfFunctions<T> = ({ [K in keyof T]: T[K] extends Method ? K : never })[keyof T];
type SelectMethods<T> = Pick<T, KeysOfFunctions<T>>;
type PromisifyFunction<T> = T extends Promise<infer U> ? Promise<U> : Promise<T>;
type PromisifyMethod<T extends Method> = (...args: Parameters<T>) => PromisifyFunction<ReturnType<T>>
type PromisifyAllMethods<T> = { [K in keyof T]: T[K] extends Method ? PromisifyMethod<T[K]> : T[K] };

type OnlyPromisifiedMethods<T> = SelectMethods<PromisifyAllMethods<T>>

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

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

What steps should I take to ensure that this test covers all possible scenarios?

I recently started learning React development and am currently exploring testing with Jest and React Testing Library (RTL). However, I'm facing challenges in achieving complete test coverage for the component code below: import { CustomCardActions, ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

ng-select search functionality failing to display any matches

Currently, I am encountering an issue with the ng-select functionality in my Angular CLI version 11.2.8 project. Despite using ng-select version 7.3 and ensuring compatibility with the Angular CLI version, the search functionality within the select eleme ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Tips for sending a timestamp as input to a stored procedure in TypeScript with the mssql module

Currently, I am utilizing the mssql npm package to communicate with SQL server. I have encountered a dilemma where the variable (which is of type TIMESTAMP in sql server) fetched from a stored procedure is returned as a byte array. Now, I need to pass this ...

Replacing `any` in TypeScript when combining interfaces

Currently using Express and attempting to explicitly define res.locals. Issue arises as in the @types/express package, Express.Response.locals is declared as any, preventing me from successfully overwriting it: types/express/index.d.ts: declare namespace ...

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

Prevent the array from altering its values

I am utilizing a mock-service that is configured in the following way: import { Article } from "./article"; export const ARTICLES: Article[] = [ new Article( 1, 'used', 5060639120949, 'Monster Energy& ...

Configuring ESLint, Prettier, and TypeScript in React Native: A Step-by-Step Guide

Could you provide guidance on setting up ESLint, Prettier, and TypeScript in React Native? I'm currently using absolute paths to specify components. Can you confirm if this setup is correct? tsconfig { "extends": "@tsconfig/react-n ...

What are the conditions for Jasmine's .toHaveBeenCalledWith to match the parameters?

I'm working on an Angular service along with its Jasmine test. The test is calling f1() and spying on f2(). The function f2 takes a variable v2 and updates it by setting field 'a' to 3. I expected the function f2 to be called with v2 (as def ...

Guide on implementing the Translate service pipe in Angular 2 code

So here's the issue... I've integrated an Angular 4 template into my application which includes a functioning translate service. The only problem is, I'm unsure of how to utilize that pipe in my code. In HTML, it's as simple as adding ...

Angular issue: Readonly or disabled input fields not submitting data

Struggling with creating a form in Angular 2 to submit dynamically generated values from a service. The goal is to calculate the equivalent amount of bitcoin for X chilean pesos using Angular's http module to fetch the price. However, facing an issue ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...

Unable to display animation without first launching it on Rive web

I attempted to incorporate a Rive animation into my Angular web application <canvas riv="checkmark_icon" width="500" height="500"> <riv-animation name="idle" [play]="animate" (load)=&qu ...

Steer clear of type assertion in your codebase when utilizing useSelector alongside Redux, Immutable.js, and TypeScript

Currently, I am working with a combination of Redux, Immutable.js, and TypeScript. I am facing challenges in obtaining proper types from the useSelector hook, which is leading me to use type assertions. I acknowledge that this is not the best practice and ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

In what ways can enhancing the TypeScript type system with additional restrictions help eliminate errors?

Encountered issues while working on my TypeScript project due to errors in the type definitions of a library. The solution was to enable the strictNullChecks flag. It seems counter-intuitive that adding restrictions can eliminate errors, when usually it&a ...

Custom Map Typescript Interface

Here is the structure of my interface: export interface IMyMap { [index: string]: RefObject<HTMLElement>; } This interface was created following the guidelines in the documentation: Indexable Types I am trying to implement this interface in a Re ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...