Guide to developing a dynamic method while utilizing IntelliSense assistance

When utilizing itemsApi in React reduxTool kit, dynamic functions like use..., mutate... are generated. These dynamically created methods possess complete intelligence as well.

For instance, if you have
createApi({...
    getItems: builder.query<any, string>({
                query: () => `items`,
            }),
...)}

Upon calling createApi, an object with methods such as useGetItemsQuery, useLazyGetItemsQuery is returned. These methods are not manually defined but constructed dynamically with intellisense support. How is this achieved in typescript?

As an illustration, how can I create a function that returns an intellisense-enabled function based on a given name?

Answer №1

If you're searching for TypeScript generics, they allow us to deduce a type from the parameter or argument.

Here's an example to illustrate this concept:

function retrieveType<T>(param: T) {
    return param;
}

const returnedValue = retrieveType({ foo:1337 });
// { foo: 1337 }

In this case, the return type of retrieveType is the same as the parameter type itself. This approach can be extended for more intricate types, such as selecting a single field only.

function extractFooOnly<T>(param: {foo: T}) {
    return param.foo;
}

const someFoo = extractFooOnly({foo: 1337});
// will be number
const someFoo2 = extractFooOnly({foo: 'bar'});
// will be string

Alternatively, we can create a function that returns an object with the value obtained from the parameter.

function obtainParamValue<T>(cb: () => T) {
    return {
        result: cb(),
    };
}

const returnValue = obtainParamValue(() => 'foo');
returnValue.result; // will be string
const returnValue2 = obtainParamValue(() => 1337);
returnValue2.result; // will be number

Moreover, we can preprocess the argument and define its return type based on processing using generics.

type ParamDataType<Key extends string, Value extends string> = {
    key: Key;
    value: Value;
} & Record<Value, true>;

function redefineType<Key extends string, Value extends string>(
    param: Record<Key, Value>
    ): ParamDataType<Key, Value> {

    const key = Object.keys(param)[0] as Key;
    const value = Object.values(param)[0] as Value;

    return Object.assign({}, {
        key: key,
        value: value,
    }, {
        [value]: true,
    } as Record<Value, true>);
}

const newData = redefineType({hello: 'world'});
newData.key; // string with value 'hello'
newData.value; // string with value 'world'
newData.world; // true without TypeScript error

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

Unable to initiate ngModelChange event during deep cloning of value

I've been struggling to calculate the sum of row values, with no success. My suspicion is that the issue lies in how I am deep cloning the row values array when creating the row. const gblRowVal1 = new GridRowValues(1, this.color, this.headList ...

Using an array of functions in Typescript: A simple guide

The code below shows that onResizeWindowHandles is currently of type any, but it should be an array of functions: export default class PageLayoutManager { private $Window: JQuery<Window>; private onResizeWindowHandlers: any; constructor () { ...

What is the reason that Jest is not able to spy on the function?

A custom Hook was developed with only one function being imported. Ensuring this function is called with the correct arguments is crucial. import { IsValueAlreadyRegistered } from "../../entities/registration/actions"; export const useForgetPass ...

Unexpected error arises in Typescript despite code functioning properly

As part of a practice project where I'm focusing on using webpack, ES6, npm and Typescript implementation, I have successfully set up loaders for 'awesome-typescript-loader' and 'babel-loader', which are bundling the code properly. ...

The behavior of the Ionic checkbox in version 5 seems to be quite delayed

I am facing an issue with binding the checked attribute value on an ion-checkbox, as the behavior seems to be delayed. In my .ts file, I have an array variable named user_id. In my checkbox list, I am trying to populate this array based on which checkboxe ...

What is the best way to utilize *ngSwitchWhen in a TypeScript environment?

I am currently working with Ionic2 and Angular2 and encountering an issue while trying to implement a segment using ngSwitchWhen. Unfortunately, the functionality is not working as expected and I am receiving an error message. How can I resolve this issue ...

Attempt to create a truncated text that spans two lines, with the truncation occurring at the beginning of the text

How can I truncate text on two lines with truncation at the beginning of the text? I want it to appear like this: ... to long for this div I haven't been able to find a solution. Does anyone have any suggestions? Thanks in advance! ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

Can you please provide the Typescript type of a route map object in hookrouter?

Is there a way to replace the 'any' type in hookrouter? type RouteMap = Record<string, (props?: any) => JSX.Element>; Full Code import { useRoutes, usePath, } from 'hookrouter' //// HOW DO I REPLACE any??? type RouteMap = ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...

Navigating a text input field in a NextJS application

Having trouble with handling input from a textarea component in a NextJS app. This is the structure of the component: <textarea placeholder={pcHld} value={fldNm} onChange={onChangeVar} className="bg-cyan-300" ...

What steps do I need to take in order for TypeScript source files to appear in the node inspector?

Currently developing a node express app with TypeScript 2.3. Compiling using tsc Interested in debugging TypeScript code using node-inspector (now included in node 6.3+) SourceMaps are enabled in my tsConfig.json file { "compilerOptions": { "targ ...

Error: React - Unable to access the 'lazy' property because it is undefined

I used a helpful guide on the webpack website to incorporate TypeScript into my existing React App. However, upon launching the app, an error message pops up saying: TypeError: Cannot read property 'lazy' of undefined The version of React being ...

How to use TypeScript to filter an array based on the values of another array

Suppose I have two arrays. The first one looks like this: names: [{ value: 'recordedData', desc: 'Data' } { value: 'recordedNumbers', desc: 'numbers' } { value: 'recordedNames', desc: 'name ...

Utilizing an API to dynamically augment a JSON object with user input in Angular

Hello, I am working on adding an input value to an object property. The scenario is that a customer wants to add an item to their shopping cart, but before adding the item, they need to choose the size. I have the form set up with validation and can retri ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

Having difficulty in utilizing localStorage to update the state

I've attempted to log back in using the stored credentials, however it's not working despite trying everything. The dispatch function is functioning properly with the form, but not when accessing localStorage. App.tsx : useEffect(() => { ...