Home > Enterprise >  Typescript returns "and" instead of "or" for parameters of functions
Typescript returns "and" instead of "or" for parameters of functions

Time:06-21

I'm currently developing a React Native app with Typescript.

I have a massive data download from server and a function for saving all data in it's corresponding table.

static insertVariousTable = (table: TypeTables) => {
    switch (table) {
      case 'clase':
        return Clase.insertVarious;
      case 'estadoequipo':
        return EstadoEquipo.insertVarious;
      case 'formapesopatron':
        return FormaPesoPatron.insertVarious;
    }
  };

When I call the function the type is: (note that the return types could be any of them, I mean "or" (|) instead of "and" (&) and that's ok for me)

let insertVarious: ((rows: ClaseType[]) => Promise<unknown>) | ((rows: TypeEstadoEquipo[]) => Promise<unknown>) | ((rows: FormaPesoPatronType[]) => Promise<...>) | undefined

But when I'm trying to call the function with await (inside an async function) it changes the types of the function parameters to "and" (&).

async function download(res:IRes){
for (key in res.data) {
    if (Object.prototype.hasOwnProperty.call(res.data, key)) {
      const tabla = res.data[key];
      let insertVarious = DbRequests.insertVariousTable(key);
      if (insertVarious) {
        await insertVarious(tabla);
      }
    }
  }
}

The "await insertVarios(tabla)" parameter type becomes: (with "and" (&))

let insertVarious: (rows: ClaseType[] & TypeEstadoEquipo[] & FormaPesoPatronType[]) => Promise<unknown>

I need the type to be "or" (|) so I can send any of them, how can I fix this?

Please help....

Thanks in advance

CodePudding user response:

Try something like this:

let insertVarious: 
   | undefined 
   | <T extends ClaseType | TypeEstadoEquipo | FormaPesoPatronType>((rows: T[]) => Promise<unknown>)

Or, if you care about the return type:

let insertVarious: 
   | undefined 
   | <T extends ClaseType | TypeEstadoEquipo | FormaPesoPatronType>((rows: T[]) => Promise<T extends FormaPesoPatronType  ? <...> : unknown>)

CodePudding user response:

Your issue is related to this issue posted on GitHub, and can be solved by defining an InsertVariousType as:

type InsertVariousType = (<T extends Array<ClaseType | TypeEstadoEquipo | FormaPesoPatronType>>(rows: T) => Promise<unknown>) | undefined

and use this type to cast the DbRequests.insertVariousTable return value as InsertVariousType.

async function download(res:IRes){
    for (let key in res.data) {
        if (Object.prototype.hasOwnProperty.call(res.data, key)) {
            const tabla = res.data[key as TypeTables];
            const insertVarious = DbRequests.insertVariousTable(key as TypeTables) as InsertVariousType;
            if (insertVarious) {
                await insertVarious(tabla);
            }
        }
    }
}

see playground

  • Related