The Problem Generics Solve
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 57 of 73.
Imagine you want to create a function that simply returns whatever value you pass to it - an "identity" function. In regular JavaScript, you might write something like this:
function identity(arg: any): any {
return arg;
}While this function works, using any creates a significant problem: you lose all type safety. When you call identity("hello"), TypeScript can't tell you that the result is a string. It only knows the result is any, which means you lose autocompletion, type checking, and all the benefits TypeScript provides.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples6Typing Objects and Interfaces
Inline Object Type AnnotationsType Aliases for ObjectsIntroduction to InterfacesInterfaces vs. Type AliasesOptional & Readonly PropsExtending Interfaces and TypesAdding Methods to InterfacesRecap: Defining Object Shapes9Generics: A First Look
The Problem Generics SolveCreating Generic Identity FuncUsing a Generic FunctionGeneric ArraysGeneric InterfacesRecap: Generic Function Prac