Issue with action creator documentation not displaying comments

We are exploring the possibility of integrating redux-toolkit into our application, but I am facing an issue with displaying the documentation comments for our action creators.

Here is our old code snippet:

const ADD_NAME = 'ADD_NAME';
/**
 * Sets the name for the user in our state.
 * @param name The updated name
 */
export function addName(name: string) {
   return {
     payload: name,
     type: ADD_NAME,
   };
}

In my VSCode environment, when I dispatch addName(), I can hover over the function to see the expected tooltip with the documentation.

Now, when trying to recreate this action creator using redux-toolkit:

/**
 * Sets the name for the user in our state.
 * @param name The updated name of the User
 */
export const addName = createAction<string>(ADD_NAME);

However, when hovering over the new addName during a dispatch, instead of seeing my written documentation:

Sets the name for the user in our state.

I encounter the following tooltip message:

Calling this {@link redux#ActionCreator} with an argument will return a {@link PayloadAction} of type T with a payload of P

This tooltip is generated from the internal documentation for ActionCreatorWithPayload within the redux-toolkit typings file.

My question is, why are the doc comments I added specifically for my addName action creator not being displayed, and instead, it shows the redux-toolkit doc comments?

Although one involves commenting a function and the other commenting a constant variable, I was expecting my comments for the addName constant to be reflected in the tooltip. What could I possibly be missing here?

Answer №1

That's an excellent inquiry. The behavior described seems to vary depending on the text editor and the specific context in which the documentation is being accessed.

In the case of VSCode, it initially appears like this: https://i.stack.imgur.com/sZNpy.png

Simply typing 'addName' will display the docblock associated with the variable until completion. Once you add a '(', the editor delves into the value of the variable, recognizes the function, and retrieves the docblock from the function definition itself - typically an action creator.

As far as I know, it may not be possible to further alter this behavior, but I'm open to seeing if someone can propose an effective solution.


After conducting additional experiments, I found that although TypeScript may not preserve most comments for mapped function types, you could opt for using a single object argument instead of positional arguments and annotate the individual properties with relevant documentation blocks. This approach likely provides the maximum amount of information available within the constraints of TypeScript at present (alongside autocomplete functionality for the "argument names"):


const slice = createSlice({
  name: 'test',
  initialState: 0,
  reducers: {
    test: {
      prepare({name, age}: {
        /** Describes the name! */
        name: string,
        /** Represents the age! */
        age: number
      }
      ) {
        return { payload: { name, age } };
      },
      reducer(x, action: any) { }
    }
  }
})

// Hovering over 'age' or 'name' will provide additional insights
slice.actions.test({ age: 5, name: "" })

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 are the benefits of utilizing TypeScript declarations? How can you demonstrate their value with concrete examples?

I'm a bit confused about the use of declaration in TypeScript. It seems like the compiler doesn't compile it into the js file, so what is the purpose and advantage of using declaration? Can someone please explain this to me? ...

unable to successfully complete parameter in angular 2

After receiving data from the API, I am using the subscribe method to execute lines of code. Below is the code snippet: this.attRecService.getAgendaData(moment(this.viewDate).format('YYYY-MM')).subscribe( resp => { this.ag ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

Get rid of the TypeScript error in the specified function

I am currently working on implementing a "Clear" button for a select element that will reset the value to its default state. Here is a snippet of my code: const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => { onChange( ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

Receiving a conduit from the fuel supplier with only limited information on hand

I am designing a service that will utilize pipes as templates. In order to accomplish this, I require access to the registered pipes. The final code structure should resemble the following: @Injectable() class MyService { constructor(private injector ...

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

Hide the MaterialTopTabNavigator from view

Is there a way to hide the react native MaterialTopTabNavigator on the screen while still maintaining the swiping functionality between screens? I want the user to be able to swipe between screens but not see the tab navigator itself. const Tab = creat ...

RTK Query may sometimes encounter undefined values when fetching data

I am new to using Redux and facing an issue while trying to display data in a Material UI Select. When I try to show the user's name, it works perfectly, but when I do the same for the partner's data, they appear as undefined. In my server index ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

Exploring the power of a mapped type within a tuple

Can TypeScript ensure the validity of key-value tuples in this function? function arrayToObject(array, mapper) { const result = {}; for(const item of array) { const [key, value] = mapper(item); result[key] = value; } return ...

How do I iterate through my state in React Redux?

Currently, I am delving into Redux by creating a to-do list in React. I have been pondering on the utilization of the map function to iterate over the state so that I can display the data stored within different div elements. Here is my initial state: cons ...

Is Typescript familiar with the import -> require syntax, but unfamiliar with the require -> import syntax?

My code includes a simple file that utilizes the ES6 module loader: 1.ts import {foo} from "./2" foo('hello'); 2.ts function foo (a){console.log(a);}; export {foo} When the tsconfig is configured as follows: "module": "commonjs", We can o ...

Transfer items on a list by dragging and dropping them onto the navigation label of the target component

I'm currently exploring how to move an element from a list to a <div> and then see it transferred to another list. The objective is to allow users to drag items from one list onto the labels in a sidebar navigation, causing the item to switch t ...

Incorporating Firebase administrator into an Angular 4 project

Currently encountering an issue while trying to integrate firebase-admin into my angular project. Despite my efforts, I am unable to resolve the error that keeps popping up (refer to the screenshot below). https://i.stack.imgur.com/kdCoo.png I attempted ...

Exploring alternative applications of defineModel in Vue 3.4 beyond just handling inputs

The examples provided for defineModel in the Vue documentation primarily focus on data inputs. I was curious if this functionality could be utilized in different contexts, potentially eliminating the need for the somewhat cumbersome props/emit approach to ...

Maintain the specific type based on the provided data, rather than the default value, when a related generic is defined

When it comes to unit tests, I prefer a more flexible approach with dynamic generic types that eliminate the need for type casting. I want T to be open-ended, but if I specify a type, I expect to receive an exact match. For R, I need it to precisely matc ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

Ways to specify an unused parameter within a function

As I work on my code, I encounter the need to separate the key and value from a request params object in order to validate the value using ObjectID. To achieve this, I decided to iterate over an array of entries and destructure the key and value for testin ...

Looking to reallocate information, paginate, and sort each time a new row is added to the mat-table

In my application, I have a customized <mat-table> with an implemented addRow() function that adds a new row to the table using default values based on the data type. The challenge I'm facing is that each time a new row is added, I find myself ...