Confusion arises from conflicting parameters when inserting a function as an argument

I am currently working on creating a function that can adapt to any informer and mapper, utilizing dependency injection to ensure the logic remains unchanged even if these components are altered. However, I seem to be encountering difficulties in generalizing my function arguments effectively.

Furthermore, when attempting to modify 'unknown' to 'any' in the signature of myFunc inform, it raises an error indicating that 'any' is not recommended and unexpected.

Interfaces

interface Document {
    name: string
}
interface Mapper {
    (doc: Document): unknown
}

Function

const myFunc = async (
    inform: (payload: unknown)=>Promise<Record<string, unknown>>,
    document: Document,
    mapper: Mapper): Promise<string> => {
  const response = <Record<string, unknown>> await inform(mapper(document));
  return response
})

Problem

class APIClient {
   async inform(payload: RequestInfo): Promise<Record<string, unknown>> {
    // Implementation
    }
}
const apiClient = new APIClient();
const result = await myFunc(
              apiClient.inform, //Issue arises as it complains about assigning unknown to RequestInfo..
              someData,
              someMapper
          );

Answer №1

unknown can pose challenges when used as a generalization tool.

If you opt to use any instead, it may compromise the type safety of your code.

In scenarios where you require generics, and you are unsure about the specific data types in advance but recognize relationships between them:

  • The mapper function should take an argument of type Document2 (note: using Document could lead to unexpected results due to potential global namespace conflicts).
  • It should return a type "P", which will be utilized by the input for inform.

You will need at least one generic type ("P" in this case):

const myFunc = async <P, R>(
    inform: (payload: P) => Promise<Record<string, R>>, 
    document: Document2,
    mapper: (doc: Document2) => P) => { 
    const response = await inform(mapper(document));
    return response
}

Here is an example with "P" being of type string:

const someData: Document2 = {
    name: 'hello'
}
const someMapper = (doc: Document2) => doc.name

const result = myFunc(
    apiClient.inform, 
    someData,
    someMapper
);

Playground Link

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

Is it possible to create a map of functions that preserves parameter types? How can variadic tuple types in TypeScript v4 potentially enhance this

Initially, I faced a challenge when trying to implement a function similar to mapDispatchToProps in Redux. I struggled with handling an array of functions (action creators) as arguments, but managed to come up with a workaround that works, although it feel ...

When checking for a `null` value, the JSON property of Enum type does not respond in

Within my Angular application, I have a straightforward enum known as AlertType. One of the properties in an API response object is of this enum type. Here is an example: export class ScanAlertModel { public alertId: string; public alertType: Aler ...

in typescript, you can cast response.value as a generic

I've implemented an agent.ts typescript file to handle API calls. const responseBody = (response: any) => response.value; const requests = { get: (url: string) => getGraphClient().api(url).get().then(responseBody) } const Activities = { ...

ReactiveX: Continuous flow of modal dialogs

My challenge is to display multiple bootstrap popups sequentially to the user, each containing a stream of messages. However, if I simply subscribe and show the messages one after the other, it might not wait for the user to dismiss a popup before showing ...

Extracting Information from ASP.Net Web API using Angular 4

After experimenting with the well-known Visual Studio 2017 Angular 4 template, I successfully tested the functionality of side navbar buttons to retrieve in-memory data. I then proceeded to enhance the project by adding a new ASP.Net Core 2.0 API controll ...

After updating to Angular 7, an error was encountered: "TypeError: Unable to execute map function on ctorParameters"

After updating my Angular project to version 7, I encountered a new issue. When running "ng serve --open" from the CLI, I received the following error message: Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities._own ...

Tips for organizing an array of objects that contain null properties

Here is an array that I need help with: "data": { "risks": [ { "id": "22", "name": true, "surname": 0.5, "age": 0.75, "heigth" ...

Troubleshooting Angular: Search Bar Woes - What's Causing the Issue?

dashboard.component.html : <div class="search-bar"> <form class="search-form d-flex align-items-center" method="POST" > <input type="text" name="query" placeholder="Search& ...

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

Module logo.svg not found? Error in Typescript

Integrating package: vue-svg-loader. Established the file svg.d.ts with the content below: declare module '*.svg' { const content: any export default content } Utilizing it in a component in the following manner: import register from &apo ...

The error message "TypeError: Object(...) is not a function" is indicating an issue when attempting to

Here is my code from addevent.ts: export class EventPage { eventDetail = {} as EventDetail; eventDetailRef$: AngularFireList<EventDetail>; constructor(public navCtrl: NavController, public navParams: NavParams, private database: AngularFireData ...

Tips for maintaining the current object's status while utilizing ngFor in Angular

The JSON data provided is structured as follows. [ { "route":"vehicle", "next-route":"driver", "isActive":false }, { "title":"Driver", "route":"driver ...

How can I stop union types from being used in TypeScript?

I'm completely new to conditional types, and I recently attempted a straightforward static approach with no success: type NoUnion<Key> = Key extends 'a' ? 'a' : Key extends 'b' ? 'b' : never; type ...

Universal loading screen across all components

I am currently implementing a loading screen for this component in conjunction with the fetch method. My concern is whether I will need to replicate the same loading logic used in the example for every component that utilizes the fetch() method, or if the ...

Is it necessary to link event handlers to `this` when using TypeScript and React?

One issue I encountered was with a component's button handler method. If the onClick handler is not bound to this in the constructor or inline on the onClick itself, an error occurs because the context of the handleAdd method is not tied to the instan ...

Is it possible to define an object literal type in typescript that permits unspecified properties?

I am looking to make sure that an object argument has all the necessary properties, while also allowing for additional properties. For instance: function verifyObject(input: { key: string }) : number { return input.key; } verifyObject({ key: 'va ...

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...

At what point does the Express req.query variable receive various types of data?

I've noticed that the req.query query parameters can be of type string, string[], QueryString.ParsedQS, or QueryString.ParsedQS[]. However, in my experience, I have only encountered strings when using req.query. Here are some questions I have: Can y ...

What is the process for assigning a value to a property?

I am currently developing an Angular application that utilizes reactive forms. I need to retrieve the values of dynamically created fields within a form group. Here is the code I have implemented: this.formSaisieSecondary = this.fb.group({ ...