Generic Functions

Generic Functions
πŸ‘¨β€πŸ’Ό We have utility functions that work with arrays, but they're limited to specific types. Let's make them generic so they work with any type.
The syntax for generic functions:
function functionName<Value>(param: Value): Value {
	return param
}
The <Value> declares a type parameter. When you call the function, TypeScript infers (or you specify) what Value is:
identity<string>('hello') // Explicit: Value is string
identity(42) // Inferred: Value is number
🐨 Open
index.ts
and:
  1. Create a generic identity function that returns its input
  2. Create a generic last function that returns the last array element
πŸ’° Use a type parameter to make the array function work with any type.

Please set the playground first

Loading "Generic Functions"
Loading "Generic Functions"