When you call the identity
function, you need to specify a single unconstrained type parameter called Type. The function takes an argument arg
of type Type
and returns a value of the same type:
function identity<Type>(arg: Type): Type {
return arg;
}
//IntelliSense suggests:
//function identity<Type>(arg: Type): Type
You can find out the type of identity
by using TypeScript's typeof
type operator:
type TypeofIdentity = typeof identity
// type TypeofIdentity = <Type>(arg: Type) => Type
The type of identity
is expressed as
<Type>(arg: Type) => Type
.
Note that Type
and arg
are just placeholders for the actual types and arguments used in the function, and you can rename them without changing the function's type. So, these declarations are equivalent to the original:
type TypeofIdentity = <T>(x: T) => T
Or this:
type TypeofIdentity = <Input>(arg: Input) => Input
This means that your myIdentity
variable has been assigned the exact same type as identity
, indicating they are equivalent functions. You can create variables with the same type, like so:
var x: typeof identity;
var x: typeof myIdentity; // allowed
var x: <T>(x: T) => T; // also valid
In essence, creating myIdentity
is similar to creating a new variable with the same value and assigning it to another variable of the same type:
const date = new Date(); // make a thing
let myDate: Date = date; // assign thing to another variable
Therefore, you can use myIdentity
in the same way as identity
since they have identical functionalities:
const str = myIdentity("str");
// const str: "str"
const tru = myIdentity(true);
// const tru: true
Playground link to code