Using a Generic Function
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 59 of 73.
There are two ways to use a generic function: with explicit type arguments or by letting TypeScript infer the type automatically.
Here's how you can call a generic function with explicit type arguments:
const result1 = wrapInObject("hello");
const result2 = wrapInObject(42);The <string> and <number> explicitly tell TypeScript what type to use for T. This gives you complete control over the type parameter.
However, TypeScript is smart enough to infer the type from the argument you pass in most cases:
const result1 = wrapInObject("hello"); // T inferred as string
const result2 = wrapInObject(42); // T inferred as numberType inference makes your code cleaner and more readable while maintaining the same type safety. TypeScript analyzes the argument and automatically determines what T should be, so you don't need to write the explicit type annotation unless you want to override the inferred type.
Challenge
EasyYou are provided with the following from the previous challenge:
- The generic function
wrapInObject<T>that takes an item of typeTand returns{ value: T }
Call the wrapInObject function using both explicit type arguments and type inference:
Using explicit type arguments:
- Create a variable
explicitStringby callingwrapInObject<string>with"TypeScript" - Create a variable
explicitNumberby callingwrapInObject<number>with25 - Create a variable
explicitBooleanby callingwrapInObject<boolean>withfalse
Using type inference:
- Create a variable
inferredStringby callingwrapInObjectwith"Generics"(let TypeScript infer the type) - Create a variable
inferredNumberby callingwrapInObjectwith99(let TypeScript infer the type) - Create a variable
inferredBooleanby callingwrapInObjectwithtrue(let TypeScript infer the type)
Print the following outputs:
- Print
explicitString.value - Print
explicitNumber.value - Print
explicitBoolean.value - Print
inferredString.value - Print
inferredNumber.value - Print
inferredBoolean.value
Try it yourself
// Generic function from previous challenge
function wrapInObject<T>(item: T): { value: T } {
return { value: item };
}
// TODO: Write your code here
// Create variables using explicit type arguments
// Create variables using type inference
// Print the resultsThis 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