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 takes a value and returns the same value (preserving its type)
  2. Create a generic last function that takes an Array<Item> and returns Item | undefined (the last element, or undefined for an empty array)
  3. Export identity and last by name

Completion criteria

  • Named exports: identity, last
  • identity returns the same value for strings, numbers, booleans, and null
  • last([1, 2, 3]) β†’ 3; last(['a', 'b', 'c']) β†’ 'c'; last([]) β†’ undefined
πŸ’° Use a type parameter to make the array function work with any type.

Please set the playground first

Loading "Generic Functions"
Loading "Generic Functions"
Login to get access to the exclusive discord channel.
Loading Discord Posts