'Function overloading in index.d.ts file
Solved: restarting VS code helped :blush:
I have a module written in es6 (not typescript) and I want to add ts declaration file to it. Module export only one function which can be called like this:
fn(A, C)
fn(A, B, C)
Here is declaration file I have for now:
/// <reference types="node" />
/// <reference types="graphql" />
declare module 'graphql-add-middleware' {
type middlewareFn = (root: any, args: any, context: any, info: any, next: () => Promise<any>) => Promise<any>;
export function addMiddleware (
schema: GraphQLSchema,
fn: middlewareFn,
): void;
export function addMiddleware (
schema: GraphQLSchema,
path: string,
fn: middlewareFn,
): void;
};
I thought that typescript will detect two variations of this function (2 or 3 args) but in a project where I am using this module ts complains if I try to addMiddleware(schema, fn)
. It says that 3 args were exepcted. It does not complain if I do addMiddleware(schema, path, fn)
.
What is wrong with my declaration file? How I can make it work?
Update - see screen below what VS code says:
Edit: you can test it by yourself - this is the package, it's published to npm: https://github.com/alekbarszczewski/graphql-add-middleware
Solution 1:[1]
I know the OP said it's solved by a VS code restart, but it didn't for me. Here's the solution that worked.
- Define each function interface as a type
- Combine the types in the actual function declaration
In your *.d.ts
type FnOverload1 = (a: string) => void;
type FnOverload2 = (a: string, b: string) => void;
type FnOverload3 = (a: string, b: string, c: string) => void;
type Fn = FnOverload1 & FnOverload2 & FnOverload3
Using Fn("a")
, Fn("a", "b")
or Fn("a", "b", "c")
no longer raises a warning or error in the IDE.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kwame Opare Asiedu |