2
interface SearchFunc {
  (source: string, subString: string): boolean;
 (source: string, subString: string,name:number): boolean;
}

Is it possible to have an interface with multiple call signatures for functions? If so, how can I implement this? Can you give me a meaningful example? Are there any use cases for this or am I thinking about / approaching this the wrong way?

1
  • In example above it would be useless, just define the name as optional: name?: number) Commented Jan 6, 2021 at 15:27

1 Answer 1

2

Here is example:


interface SearchFunc {
    (source: string, subString: string): boolean;
    (source: string, subString: string, name: number): boolean;
}

const fn: SearchFunc = (source: string, subString: string, name?: number) => true

But, in your case You don't need such interface. THis technique called overloading

Overloadings are useful, if you have some constraints.

For example, your return type is dependent on third argument:

interface SearchFunc {
    (source: string, subString: string): boolean;
    (source: string, subString: string, name: number): string;
}

const fn: SearchFunc = (source: string, subString: string, name?: number) => null as any

const result = fn('sdf','sdf', 2) // string

const result1 = fn('sdf','sdf') // boolean

Or next:

interface SearchFunc {
    (source: string, subString: number): boolean;
    (source: number, subString: string): string;

}

const fn: SearchFunc = (source: string | number, subString: string | number) => null as any

const result = fn('sdf', 2)

const result1 = fn(2, 'sdf')

const result2 = fn(2, 2) // error

const result3 = fn('2', '2') // error

Type of function allows fn(2, 2), but insterface not. Interface SearchFunc has higher priority here.

Typed arguments: (source: string | number, subString: string | number) just should be compatible with interface.

Because, according to interface source argument could be either string or number, we should also define it in function signature as string | (or) number

Sign up to request clarification or add additional context in comments.

3 Comments

const result2 = fn(2, 2) // error const result3 = fn('2', '2') // error.. why this two are errors.The above function is having call signature with four possible combination know. Actually I am new to this symbol "I" i am having trouble understanding that
@somanraj I made an update . More info you will find in docs typescriptlang.org/docs/handbook/functions.html#overloads
you are superb.Your addition to answer makes more meaning

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.