lundi 1 avril 2019

Typescript invoke function from object index with generic type

I'm trying to use generics in Typescript in a way that a generic parameter will be used as an index to call a function stored in an object.
The error I'm receiving is:

[ts] Cannot invoke an expression whose type lacks a call signature. Type '((variable: { insertId: number; }) => string) | ((variable: { updateId: number; value: string; }) => string) | ((variable: { deleteId: number; }) => string)' has no compatible call signatures. [2349]

Here's a sample code that replicates the issue:

type Query = "insert" | "update" | "delete";

interface QueryInput {
  insert: { insertId: number };
  update: { updateId: number; value: string };
  delete: { deleteId: number };
}

type QueryObject = { [T in Query]: (variable: QueryInput[T]) => string };

const queries: QueryObject = {
  insert: variable => "insert",
  update: ({ updateId, value }) => "update",
  delete: variable => "delete"
};

const getQuery = <T extends Query>(query: T, variables: QueryInput[T]) => {
  return queries[query](variables); // this line throws an error
}

It seems as if the Typescript engine cannot resolve the correct signature of the function - although there is definitely only 1 possible signature (the one returned from queries[query]).
It seems that query and variables are resolved correctly, and have the appropriate types.




Aucun commentaire:

Enregistrer un commentaire