Capable of being assigned to a particular type, although it may also be utilized with an

I'm aiming to enhance an MSW resolver by applying response composition and creating a new resolver.

import {
  ResponseResolver,
  context,
  createResponseComposition,
  response
} from "msw";

export const createDelayedComposer = <
  M extends ResponseResolver<any, any, any>
>(
  milliseconds: number
) => {
  const delayed = createResponseComposition(undefined, [
    context.delay(milliseconds)
  ]);
  return (resolver: M): M => (req, _, ctx) =>
    resolver(req, Object.assign(delayed, response), ctx);
};

Encountering the following error:

Type '(req: any, _: ResponseComposition<any>, ctx: any) => AsyncResponseResolverReturnType<MockedResponse<any>>' is not assignable to type 'M'.
  '(req: any, _: ResponseComposition<any>, ctx: any) => AsyncResponseResolverReturnType<MockedResponse<any>>' is assignable to the constraint of type 'M', but 'M' could be instantiated with a different subtype of constraint 'ResponseResolver<any, any, any>'.ts(2322)

CodeSandbox

I've looked into similar solutions but I'm having trouble understanding my mistake. Can anyone identify what's wrong with my signature, and suggest a fix?

Alternatively, perhaps there's another approach to achieve the objective of enhancing the resolver function

Answer №1

I believe that the call signature you are using is being unnecessarily complicated.

In Summary

import { createResponseComposition, context } from 'msw'

export function customizedResponse() {
  
}

export const customizedResponse = createResponseComposition(undefined, [
  context.delay(500)
])
import { customizedResponse } from './customizedResponse'

export const handlers = [
  rest.get('/resource', (req, res, ctx) => {
    return customizedResponse(ctx.text('Hello world'))
  })
]

It's important to understand that custom response composition serves to streamline repetitive actions. Your current code suggests that the delay duration may vary dynamically, making a custom response composition unnecessary. Instead, utilizing ctx.delay() on an individual response basis would be more efficient:

rest.get('/resource', (req, res, ctx) => {
  return res(ctx.delay(500), ctx.text('One'))
}),
rest.post('/login', (req, res, ctx) => {
  return res(ctx.delay(250), ctx.text('One'))
})

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 is the appropriate Typescript return type to use for a $http request that only returns a successful response with no content?

I recently developed a Typescript service: class SettingsService implements ISettingsService { public info = {}; public backupInfo = {}; public userConfig = {}; public isLoaded = false; constructor( private $http: ng.IHttpSer ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

Take a look at the browser's view

Are there any methods to monitor changes in the browser window using an Observable, such as rxJS or a similar tool? I am interested in triggering an action whenever the browser window is resized. ...

Best practices for implementing dual ngFor directives within a single tr element?

Click here to view the page The image attached shows the view I want to iterate through two ngFor loops inside the tr tag. When using a div tag inside the tr, it's looping the button next to the tag instead of where I want it in the file table header ...

Angular6 - accessing elements that are not visible on the page

Currently, I am facing a situation where I have a component embedded in my HTML template that needs to remain hidden until a certain condition is met by checking a box. The tricky part is that the condition for setting "showControl" to true relies on calli ...

Fairly intricate React function component declaration with TypeScript

const withAuth = () => <OriginalProps extends {}>( Component: React.ComponentType<OriginalProps & IAuthContextInterface> ) => { } (withAuth()(PrivateRoute)) // this is how the HOC called Could someone simplify what this function d ...

Build a Node.js application using TypeScript and all necessary dependencies

I've developed a Node.js application using TypeScript and now I'm looking to compile it. Currently, only the source files in the src folder are included in the build. However, I also want to incorporate dependencies such as express, body-parser, ...

Mastering the art of chaining HTTP requests with RxJS for optimal results

I have a task that involves making multiple HTTP calls sequentially, examining the result of each call before proceeding to the next one. Depending on the response, I may need to display a message, continue to the next call, or break the chain. Additionall ...

Creating reducers for a unique data type: A step-by-step guide

Today, I was working on enhancing a shopping website using React Typescript and Context API. My goal is to utilize React Reducers to manage the state of my Shopping Cart. I have custom Types defined for the Product type, which includes an Items Array and s ...

Encountering an error while attempting to modify the state of an array of objects in a React Typescript

Recently delving into Typescript, I encountered an issue while attempting to insert a new object into the array within React state. The error message reads as follows: Type '{ name: string; address: string; }[] | null' is not an array type.ts(246 ...

Organize data by month and year using Underscore.js groupBy method

This is my JSON Input: "data": [ { "id":3, "created_by": 1, "created_at": "2022-01-31T07:00:01.880Z", }, { "id":2, ...

Adding a timestamp or hash as a request parameter for css or js files in the NextJS 12 build file can be accomplished by simply including "?ts=[timestamp]" in the file

It is important for me to be able to generate the following JavaScript and CSS file names with timestamps after building a NextJs application: ./path/file.js?ts=[timestamp] ./path/file.css?ts=[timestamp] ...

Utilizing TypeScript to define the parameter of a method within a generic interface by extracting a value from the generic type

In search of defining a versatile interface that can manage any Data type, I came up with an idea. This interface includes a dataKey property which simply holds a value of keyof Data. Additionally, it features a handler function where the parameter type sh ...

Having trouble establishing a connection with mongoose and typescript

When attempting to establish a connection using mongoose, I consistently encounter the errors outlined below. However, if I use MongoClient instead, everything functions as expected. import connectMongo from '../../lib/connectMongo' console.log( ...

Utilize NestJS to consume EventPattern exclusively when the header variable matches a specific value

I've been working on a NestJS project where I'm using a Kafka server to emit events and NestJS to consume them. My goal is to create a consumer with the topic my-topic that is triggered only when a specific value is present in the header variable ...

Error encountered while using TypeScript in the React Context Provider

I'm currently working on setting up an auth/session context for my application. However, I've encountered some issues while trying to create the Provider component and pass children as props. const AuthContext = createContext({}) type Props = { ...

Fire the BehaviorSubject with the identical value following a mutation

I am working with a BehaviorSubject where I have to make changes through mutation (for reasons beyond my control). I need to trigger the BehaviorSubject for subscriptions whenever there are changes. Is there another approach I can take instead of using: ...

unable to locate the nested routes in the folder for remix

Hey there, I've been using the remix to create a basic page and I'm trying to organize the routes using folders. Here is my project directory: - app/ - root.tsx - examples/ - route.tsx - child1/ - account.tsx In the examples di ...

Patience is key as you await the completion of an API call in Angular 14

Within my Angular 14 application, I am faced with a scenario where I need to make two API calls and then combine the results using "combineLatest" from rxjs. The combined data is then assigned to a variable that I must use in a separate function. How can I ...

Deciphering the SessionProvider error: When "useSession" isn't recognized as a function

I recently started diving into React and NextJS, but I've been able to piece things together with the knowledge I have. Recently, I added social login functionality using Lucia auth and now I'm looking to implement a session provider to allow ac ...