1

I am reading the Typescript Handbook - Generics, and there is a snippet of code as the following:

interface GenericIdentityFn {
    <T>(arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity;

I would like to know why can I assign identity (which is a Function) to a variable with type GenericIdentityFn (which is an Interface)?

3
  • 2
    Because the interface is of a function? It has the callable signature, as explained in the interface docs. Commented Feb 10, 2019 at 22:40
  • @jonrsharpe Why not add that as an answer, seems like a good one :) Commented Feb 10, 2019 at 22:43
  • @TitianCernicova-Dragomir because it's a tautology explained in the official documentation? The function meets the interface because it's the interface of a function. Commented Feb 10, 2019 at 22:45

2 Answers 2

3

When an interface follows this pattern:

interface Callable {
  (): any
}

it's said that anything that implements this interface is callable or has a call signature. It's a fancy way to describe functions and methods. There are other variations of that notation:

interface GenericCallable<T> {
  (): T
}
interface Newable {
  new (): any
}
interface GenericNewable<T> {
  new (): T
}

where the ones with the new keyword are newable, which means they are called using the new keyword (like classes).

You can also have an interface which is callable and newable at the same time. The Date object built into the standard library is one of them:

interface DateConstructor {
    new(): Date;
    (): string;
}

Long story short, interfaces can also describe functions and GenericIdentityFn is an example of such an interface.

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

Comments

1

This is because in Typescript, you can define function types via interfaces with a callable signature using parenthesis.

Interfaces are capable of describing the wide range of shapes that JavaScript objects can take. In addition to describing an object with properties, interfaces are also capable of describing function types.

See the Typescript doc about this feature.

In your case identity has the same signature as the type defined by GenericIdentityFn since the interface defines a callable signature that takes an argument of type T and returns a T.

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.