Generics

A generic function accepts parameter types alongside its regular parameters.

The easiest generic function to create is the identity function, which simply returns its first argument.

We can modify this function to use the any type, which indicates that it works correctly for any possible input (it does!)

Notice that the type of x in the program above is any, even though it should be fairly obvious that the result will be of the same type string. To allow TypeScript inference to "pass through" the function, we can define a type variable after the function name to capture information about the first parameter's type.

Notice that x is now correctly typed as a string, and will receive the same type that TypeScript inferred for the first argument 'hello'.

There may be situations where you need to explicitly tell TypeScript what the first parameter's type is.

Just as with function parameters, type parameters can be assigned a default value.

Was this page helpful?