1

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"));

1 Answer 1

4

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"));
Sign up to request clarification or add additional context in comments.

Comments

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.