id
The identity function
Last updated
The identity function
Last updated
Literally just:
It directly returns the parameter it was given as input.
If we don't use id
, Cat["gender"]
is of type string
We could have used "male" as "male" | "female"
But this is less type safe because we do not validate that the value that we gives to gender is actually assignable to "male" | "female".
This error for example slips through:
Let's say you have this function:
And let's say a shape object is defined as follows:
We want to instantiate a Circle
and pass it to getArea
we can do:
If we want to avoid declaring a variable, we can do
The problem, however, is that this Circle
was not as easy to instantiate because TypeScript doesn’t know what kind of shape we are trying to instantiate:
id lets you declare that the shape you are instantiating is a Circle