Utilize the class type of a method parameter as the method type for another parameter

Here's a quick example illustrating my desired functionality.

// Every time, the ACL class will have a different name such as "UsersACL", etc.
export class EventsACL {
    test(): { read: true, write: true } {
        
    }
}

// This function acts as a decorator for other methods
function ACL(obj: {
    aclClass: any,
    wantedProperties: aclClass.test
});


// Calling it
ACL({ acl: EventsACL, { read: true, write: false });

This means that if I modify the EventsACL test function, it should dynamically update the request value in wantedProperties. I prefer not to use predefined interfaces as I want this to be adaptable for any class.

Answer №1

If you're looking to achieve something similar, there's a technique you can use. The workaround we apply to determine the return type of test may seem unconventional, but rest assured that the method itself won't actually be invoked during runtime. You can experiment with this concept on the TypeScript playground:

var dummy = (false as true) && EventsACL.prototype.test();
is functionally valid because TypeScript's type checker assumes the function evaluation process, even though in JavaScript it simplifies to
var dummy = false && EventsACL.prototype.test();
, preventing actual execution at runtime.

export class EventsACL {
  test(): {
    read: boolean,
    write: boolean
  } {
    return {
      read: true, write: false
    }
  }
}

// `aclObj` in this context refers to any typed object featuring a `test` method — like an instance of EventsACL or UsersACL.
var dummy = (false as true) && aclObj.test();
type ReturnType = typeof dummy;

function ACL(obj: {
  aclClass: any,
  wantedProprties: ReturnType
}) {

}

ACL({
  aclClass: EventsACL,
  wantedProprties: {
    read: true,
    write: false
  }
});

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

Angular: encountering template parse errors with unknown <component> element

I'm struggling to import a component into another component, but the imported component cannot be found. Here is the error message: Uncaught Error: Template parse errors: 'aktenkorrespondenzenTemplate' is not a known element: 1. If 'ak ...

Changing the Image Source in HTML with the Power of Angular2

Despite my efforts, I'm unable to display the updated image in my HTML file. In my TypeScript file, the imageUrl is updating as expected and I've verified this in the console. However, the HTML file is not reflecting these changes. In my researc ...

Angular 2 Update RC5: Router Provider Not Found

I'm encountering an issue with the latest Angular 2 RC5 router (router version is RC1). Below is the error log from the dev console: EXCEPTION: Error in /templates/app.component.html:2:0 ORIGINAL EXCEPTION: No provider for Router! This is how my ap ...

Repeated calls to Angular's <img [src]="getImg()"> frequently occur

Can someone help me figure out what's going on here? Recently, I set up a new Angular project and in app.component.html, I have the following code: <img [src]="getDemoImg()"> In app.component.ts: getDemoImg(){ console.log('why so m ...

Display a modal dialogue with an image on the initial page load for each user

Working on a project with Angular 11, Angular material, and Bootstrap, I encountered an issue. I want to display a popup ad the first time a user visits the home page. The modal dialog is created using Angular material, and I have it in the ads component, ...

Issue with PrimeReact dropdown component not recognizing an array in TypeScript

Trying to incorporate the PrimeReact Dropdown component in a NextJs app with TypeScript. Encountering an error when attempting to select options from the dropdown list: "Objects are not valid as a React child (found: object with keys {name, code})" The b ...

What is the best way to determine if several simultaneous tasks have been completed?

Implementing multiple parallel actions in an Angular component has proven to be challenging for me. Following each action (foo), I subscribe to its result. I've been attempting to determine if any actions are currently running or have completed using ...

What is the best approach for defining variables in typescript?

Let's talk about creating a variable for a car: export class ICar { wheels: number; color: string; type: string; } So, which way is better to create the variable? Option one: const car = { wheels: 4, color: 'red', type: &apos ...

What sets apart the ? operator from incorporating undefined in the type declaration?

Can you explain the distinctions among these options? type A = {a?: string} type A = {a: string | undefined} type A = {a?: string | undefined} In what scenarios would one be preferred over the others? For more information, visit: https://github.com/mic ...

Using Generic Types in TypeScript Files for React Components

I have encountered an issue that I haven't been able to find a solution for online. When I define a function in a ts file like this: const lastGeneric = <T>(arr: Array<T>): T => { return arr[arr.length - 1]; } But when I try to do ...

Utilize the provider within the decorator function

Essentially, the challenge I am facing is passing an authService to the "verifyClient" function within the @WebSocketGateway decorator. Here is how it should look: @WebSocketGateway({ transports: ['websocket'], verifyClient: (info: { req: Inc ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

Exploring the concept of object inheritance in Angular 5 with Typescript

I'm facing a challenge related to inheritance while building my initial angular 5 application. The error message I encounter is: Property 'message' does not exist on type 'CouponEvent', as reported by the angular-cli. export class ...

Issue with SignalR client functionality following update to .NET Core 3.1版本

Upon updating our server-side code to asp.net core 3.1, we encountered an issue with the javascript client for signalr (@microsoft/signalr 3.1.0). The errors we are facing are: https://i.sstatic.net/ITZyK.png Here is the code snippet for the hub initial ...

Exploring Polymorphism in Typescript through Data Model Interfaces

Seeking out a design pattern for the following scenario: IApp.ts export interface IApp { platform: PlatformEnum; version: string; islive: boolean; title: string; iconurl: string; } IAppleApp.ts export interface IAppleApp extends IApp { ...

Can a Typescript type alias be altered in real time?

Currently, I am developing an Angular library that will function as an API client. The challenge I am facing is that some of the applications utilizing this library are configured with an HttpInterceptor to automatically transform date strings into JavaScr ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Error message: "Lazy-loaded modules encounter a TypeError stating that '' is not a function when accessed through NGINX."

Hey, I've got some distribution files for you to check out: AOT-enabled dist with Lazy Modules No AOT Lazy Modules dist AOT without Lazy Modules dist Here's what's been going on: When served locally with webpack-dev-server or live-serve ...

Submitting information to a server

I have a simple Angular 6 app with follow and unfollow buttons. When you click follow, the number increases. I want to save these follower numbers to a JSON server. Here is the link to the JSON server documentation: JSON Server Documentation To see a dem ...

What are the steps to resolve the error message "Make sure the component is enclosed within a <Provider>" while using Next 14 with Redux Toolkit?

I've been struggling to get Next.js 14 to work with Redux Provider. I followed all the guidelines on the Redux official documentation here, but I keep encountering this error: Error: could not find react-redux context value; please ensure the compo ...