Reputation: 1236
I want to have multiple call signatures in an interface, such that they have different generic arguments
interface GenericIdentityFn {
<T>(arg: T): T;
<T, F>(arg1: T, arg2: F): [T, F];
}
function identity<T>(arg: T): T {
return arg;
}
// error: duplicate definition
function identity<T, F>(arg1: T, arg2: F): [T, F] {
return [arg1, arg2];
}
let myIdentity: GenericIdentityFn = identity;
console.log(myIdentity("hello"));
Upvotes: 1
Views: 1601
Reputation: 249636
You can't have multiple implementations of a function. You can have a function with multiple signatures, but one implementation and it is up to you in the implementation to discern the signature that was called.
If you define the function with multiple overloads you will be able to assign it to the GenericIdentityFn
interface
interface GenericIdentityFn {
<T>(arg: T): T;
<T, F>(arg1: T, arg2: F): [T, F];
}
function identity<T>(arg: T): T;
function identity<T, F>(arg1: T, arg2: F): [T, F]
function identity<T, F>(arg1: T, arg2?: F): T | [T, F] {
return typeof arg2 === 'undefined' ? arg1 : [arg1, arg2];
}
let myIdentity: GenericIdentityFn = identity;
console.log(myIdentity("hello"));
Upvotes: 4