1
function identity<Type>(arg: Type): Type {
  return arg;
}
 
let myIdentity: <Input>(arg: Input) => Input = identity;

I understand from the code that, the 'identity' function takes an argument of generic type. I don't understand what's happening after the function. How is 'myIndentity' assignment working?

1
  • identity and myIdentity are equivalent functions, just using different syntaxes. Commented Oct 6, 2021 at 14:34

1 Answer 1

1

So, identity is a generic function which, when called, must be specified with a single unconstrained type parameter Type; this function then takes a single function parameter arg of type Type, and returns a value of type Type:

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

//IntelliSense says this:
//function identity<Type>(arg: Type): Type

You can get the type of identity by using TypeScript's typeof type operator (not to be confused with JavaScript's typeof operator):

type TypeofIdentity = typeof identity
// type TypeofIdentity = <Type>(arg: Type) => Type

So identity's type can be written as the generic function type expression <Type>(arg: Type) => Type.

Note that Type is just the name of a type parameter and arg is just the name of an argument, and these names can be changed without changing the type of identity. Meaning the following is completely equivalent to the version you have:

type TypeofIdentity = <T>(x: T) => T

Or this:

type TypeofIdentity = <Input>(arg: Input) => Input

That means your myIdentity variable has been annotated with a type completely equivalent to the type of identity, and you assign identity to myIdentity. So myIdentity has the same value as identity, and you have annotated them as the same type.

You can prove this to yourself by declaring a var of each type; TypeScript will let you re-declare vars but only if the subsequent declarations are of the same type. The fact that the following compiles means the compiler sees no important difference between the type of identity, the type of myIdentity, or <T>(x: T)=>T:

var x: typeof identity;
var x: typeof myIdentity; // okay
var x: <T>(x: T) => T; // okay

Anyway, fundamentally what you've done is made a value and then assigned that value to a new variable of the same type. In some sense it's no different from:

const date = new Date(); // make a thing
let myDate: Date = date; // assign thing to another variable

And that means you can use myIdentity the same way you could use identity; they are the same thing, after all:

const str = myIdentity("str");
// const str: "str"
const tru = myIdentity(true);
// const tru: true

Playground link to code

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.