Create a new object containing a series of function expressions, but exclude the first function parameter

In my current setup, I have a variable called storePattern

const storePattern = {
  state: {
  },
  mutations: {
  },
  actions: {},
  modules: {
    modal: {
      actions: {
        openModal(store, name: string): boolean {
          console.log('Opening Modal', name);
          return true;
        },
        closeModal(store, name: string): boolean {
          console.log('Closing Modal', name);
          return true;
        },
      }
    }
  }
};

Current Status: The types for

storePattern.modules.modal.actions
currently look like this

(property) actions: {
    openModal(store: any, name: string): boolean;
    closeModal(store: any, name: string): boolean;
}

Objective: My goal is to redefine the types so that it skips the first argument and becomes:

(property) actions: {
    openModal(name: string): boolean;
    closeModal(name: string): boolean;
}

I have found a solution that works when actions is a standalone variable

const actions = {
  openModal(store, name: string): boolean {
    console.log('Opening Modal', name);
    return true;
  },
  closeModal(store, name: string): boolean {
    console.log('Closing Modal', name);
    return true;
  }
}

type TypedActions = {
  [Property in keyof typeof actions]: (arg: Parameters<typeof actions[Property]>[1]) => ReturnType<typeof actions[Property]>;
}

However, the same approach does not work for the storePattern object.

type StorePattern = {
  state: any;
  getters: any;
  mutations: any;
  actions: {
    [ModuleProperty in keyof typeof storePattern['modules'] as ModuleProperty]: {
      [ActionProperty in keyof typeof storePattern['modules'][ModuleProperty]['actions']]: (arg: Parameters<typeof storePattern['modules'][ModuleProperty]['actions'][ActionProperty]) => ReturnType<typeof storePattern['modules'][ModuleProperty]['actions'][ActionProperty]>;
    }
  };
};
Type '{ modal: { actions: { openModal(store: any, name: string): boolean; closeModal(store: any, name: string): boolean; }; }; }[ModuleProperty]["actions"][ActionProperty]' does not satisfy the constraint '(...args: any) => any'.
  Type '{ modal: { actions: { openModal(store: any, name: string): boolean; closeModal(store: any, name: string): boolean; }; }; }[ModuleProperty]["actions"][keyof { modal: { ...; }; }[ModuleProperty]["actions"]]' is not assignable to type '(...args: any) => any'.
    Type '{ modal: { actions: { openModal(store: any, name: string): boolean; closeModal(store: any, name: string): boolean; }; }; }[ModuleProperty]["actions"][string] | { ...; }[ModuleProperty]["actions"][number] | { ...; }[ModuleProperty]["actions"][symbol]' is not assignable to type '(...args: any) => any'.
      Type '{ modal: { actions: { openModal(store: any, name: string): boolean; closeModal(store: any, name: string): boolean; }; }; }[ModuleProperty]["actions"][string]' is not assignable to type '(...args: any) => any'.

As I am still learning TypeScript, my approach may not be perfect. I'm open to any feedback as well :)

Answer №1

Here is what you may be looking for:

  interface ModuleStorePattern = typeof moduleStore['pattern'];

  interface ModuleStore {
    state: any;
    getters: any;
    mutations: any;
    actions: {
      [Module in keyof ModuleStorePattern]: {
          [ModuleKey in keyof ModuleStorePattern[Module]]: {
            [Key in keyof ModuleStorePattern[Module][ModuleKey]]: (argument: Parameters<ModuleStorePattern[Module][ModuleKey][Key]>[1]) => ReturnType<ModuleStorePattern[Module][ModuleKey][Key]>
          }
      }
    };
  };

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

``Can someone provide guidance on how to showcase the validation check result for a text-field in the snackbar using Vuet

One of the challenges I'm facing in my project is implementing a validation function for the customer form. While using the vuetify validate method would be the easy way to go, I need to display the validation messages both as snackbar and next to eac ...

Solving the issue of loading Ember Initializers during the transition to TypeScript

While following the ember quick start tutorial, I attempted to switch from Javascript to Typescript. Converting the .js files to .ts files resulted in an error with the ember-load-initializers import. The application is unable to run until this issue is re ...

What is the correct way to invoke a method from a generic in TypeScript?

My goal is to develop a function that invokes a specific method on a generic object. Here's my initial attempt: type MethodName<S extends Object, M extends keyof S> = S[M] extends Function ? M : never const callMethod = <S, M extends keyof ...

Managing data with Angular 2: Setting and retrieving values

In my current project, I am working on developing a service that can parse data to different components based on various routes. When I call this service within the same component, everything works as expected and I get the desired results. However, when ...

How can I set up BaconJS in conjunction with Webpack and CoffeeScript?

Currently in the process of transitioning old code to Webpack and encountering some issues... Utilizing a dependency loader in TypeScript import "baconjs/dist/Bacon.js" And a module in CoffeeScript @stream = new Bacon.Bus() Upon running the code, I en ...

Ways to break down a collection of multiple arrays

Looking to transform an array that consists of multiple arrays into a format suitable for an external API. For example: [ [44.5,43.2,45.1] , [42, 41.2, 48.1] ] transforming into [ [44.5,42], [43.2,41.2] , [45.1, 48.1] ] My current code attempts this ...

I am experiencing difficulties with implementing Angular material components in my project

I recently encountered an issue while trying to integrate angular material into my project. Despite importing the MatFormFieldModule, I received the following error: ERROR in src/app/login/components/login/login.component.html:2:1 - error NG8001: &apo ...

When I declare a second service in the constructor, my modal service no longer opens as expected

Recently, I came across this login method in Angular: email: string = ""; password: string = ""; login() { const credentials = { email: this.email, password: this.password }; this.userService.login(credential ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

Adding data-attributes to a Checkbox component using inputProps in React

Utilizing Fabric components in React + Typescript has been a breeze for me. I have been able to easily add custom attributes like data-id to the Checkbox component, as documented here: https://developer.microsoft.com/en-us/fabric#/components/checkbox Howe ...

Error in Typescript: An element is implicitly assigned the 'any' type because a string expression is being used to index a different type

Hello everyone, I'm fairly new to TypeScript and I've been struggling to troubleshoot an error in my code. Can someone please assist me with solving this TypeScript error? I keep getting the error message: "Element implicitly has an 'any&a ...

The variable 'selectedvalue' is being accessed before it has been initialized

I'm currently working on sharing the date between components using BehaviorSubject, but I'm encountering an error in the process. public data = new BehaviorSubject<any>(this.selectedValue); public sharedData = this.data.asObservable(); sele ...

Angular 17 Pokedex Encyclopedia

Recently, I tackled a challenge during my Boot Camp where I had to create a Pokedex using pokeapi. After successfully completing the challenge, I decided to refine some aspects of it. However, I encountered an unusual issue when delving into the details of ...

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Include a Polyfill in craco, implementing a fallback for 'resolve.fallback'

I'm encountering an issue: If you need to use a polyfill, follow these steps: - include a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }' - install 'path-browserify' If you prefer n ...

Retrieve data from submit button in Angular and use it as a parameter to invoke a function

I am working on a HTML file that includes a dropdown list: <select> <option *ngFor="let t of items" value="t"> {{ t }} </option> </select> In addition to the dropdown list, there ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

Different varieties of TypeScript's keyof when working with objects

I am grappling with the concept of TypeScript's types when incorporating the keyof type operator on objects. Check out this example: type TypeA = { [k: number]: boolean }; type AKey = keyof TypeA; // ^? type AKey = number type TypeB = { [k: string] ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...