MSW V2 - Move Generic Arguments and Body Type Casts

verified codemod icon

This automation puts the generic arguments in the correct order to keep type safety.

MSW
ts-morph
Estimated time saving
Up to 15 minutes/occurrence
Change mode
Assistive
Applicability criteria

MSW version >= 1.0.0

Made by
Codemod.com
Codemod.com

Usage →

Codemod CLI:

intalling vs code extension tooltip icon
codemod msw/2/type-args
copy CLI command icon

Codemod VS Code extension:

intalling vs code extension tooltip icon
vs code logo
Run in VS Code

Description

There is a change to generic type interface of rest.method() calls. This codemod puts the generic arguments in the correct order to keep type safety.

WARNING

This codemod runs .fixUnusedIdentifiers() on a source file you are running it on. This would remove any unused declarations in the file. This is due to atomicity of this mod, which blindly inserts the callback structure into each msw handler callback and then cleans up the variables that are not used.

Example

Before

http.get<ReqBodyType, PathParamsType>('/resource', (req, res, ctx) => {
  return res(ctx.json({ firstName: 'John' }));
});

After

http.get<PathParamsType, ReqBodyType>('/resource', (req, res, ctx) => {
  return res(ctx.json({ firstName: 'John' }));
});

Before

http.get<ReqBodyType>('/resource', (req, res, ctx) => {
  return res(ctx.json({ firstName: 'John' }));
});

After

http.get<any, ReqBodyType>('/resource', (req, res, ctx) => {
  return res(ctx.json({ firstName: 'John' }));
});

Before

const handlers: RestHandler<DefaultBodyType>[] = [
  http.get('/resource', (req, res, ctx) => {
    return res(ctx.json({ firstName: 'John' }));
  }),
];

After

const handlers: HttpHandler[] = [
  http.get<any, DefaultBodyType>('/resource', (req, res, ctx) => {
    return res(ctx.json({ firstName: 'John' }));
  }),
];

Before

export function mockFactory(
  url: string,
  resolver: ResponseResolver<
    MockedRequest<{ id: string }>,
    RestContext,
    Awaited<ImportedPromiseBodyType>
  >,
) {
  return http.get(url, resolver);
};

After

export function mockFactory(
  url: string,
  resolver: ResponseResolver<
    HttpRequestResolverExtras<PathParams>,
    { id: string },
    Awaited<ImportedPromiseBodyType>
  >,
) {
  return http.get(url, resolver);
};