Home > other >  is there a way to type compare methods of 2 typescript modules?
is there a way to type compare methods of 2 typescript modules?

Time:11-28

examples:

api.ts

export const getStuffs = async (term:string): Promise<Stuff[]> => {
   const stuffs = await getStuffsFromDB(term);
   return stuffs;
}

mock_api.ts

export const getStuffs = async (term:string): Promise<Stuff[]> => {
   const stuffs = [
     { ... hardcoded stuff }
   ];
   return stuffs;
}

is there a way to add in a CI/CD test to compare that the two provided example module above are equal in type input/output: (term:string):Promise<stuff[]> ?

The objective is to automatically remind devs to always replicate the exported methods in api.ts to be mocked in mock_api.ts

CodePudding user response:

Using the two generic helper types IfEquals and BeTrue, we can check at compile time if two types are equal.

type IfEquals<T, U> =
  (<G>() => G extends T ? 1 : 2) extends
  (<G>() => G extends U ? 1 : 2) ? true : false;

type BeTrue<T extends true> = T

Import both functions into a single file but be sure two give one of them an alias to avoid the naming collision.

You can now check the two function types for equality.

declare let res: BeTrue<IfEquals<typeof getStuffs, typeof getStuffs2>>

This line will emit a compile time error if the types are not equal.


Playground

CodePudding user response:

The objective is to automatically remind devs to always replicate the exported methods in api.ts to be mocked in mock_api.ts

You don't really need CI/CD to check this for you, instead you could simply create a interface that defines the methods you need:

interface ApiMethods {
    getStuffs: (term: string) => Promise<any[]>
}

Then create an object in each of your files that implement this interface:

const apiMethods: ApiMethods = {
    getStuffs: async () => {
        return new Promise((resolve, reject) => {resolve([])});
    }
}

const mockMethods: ApiMethods = {
    getStuffs: async () => {
        return new Promise((resolve, reject) => {resolve([])});
    }
}

Adding a new method/property to ApiMethods will now force you to implement those in apiMethods and mockMethods.

  • Related