Creating Generic Identity Func
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 58 of 73.
Here's the syntax for a generic function using the classic identity example:
function identity(arg: T): T {
return arg;
}The <T> after the function name declares a type parameter called T. This T acts as a placeholder that can represent any type. When you use this function, TypeScript will replace T with the actual type you're working with.
The beauty of this approach is that it preserves type information.
If you call identity("hello"), TypeScript knows the return type is string. If you call identity(42), it knows the return type is number.
You get all the flexibility of working with multiple types while keeping full type safety.
By convention, T stands for "Type," but you can use any name you want for your type parameter. The important thing is that it creates a relationship between the input and output types of your function.
Challenge
EasyCreate a generic function named wrapInObject that takes an argument of any type and returns an object containing that value.
The function should:
- Use a generic type parameter
T - Accept one parameter named
itemof typeT - Return an object with a single property
valueof typeT - Have an explicit return type annotation
Create the following variables to test your function:
wrappedString- callwrapInObjectwith the string"Hello TypeScript"wrappedNumber- callwrapInObjectwith the number42wrappedBoolean- callwrapInObjectwith the booleantrue
Print the following outputs:
- Print
wrappedString.value - Print
wrappedNumber.value - Print
wrappedBoolean.value - Print the result of calling
wrapInObjectwith the string"Generic", accessing thevalueproperty - Print the result of calling
wrapInObjectwith the number100, accessing thevalueproperty
Try it yourself
// TODO: Write your code here
// Create the generic function wrapInObject
// TODO: Create the test variables
// wrappedString, wrappedNumber, wrappedBoolean
// Print the outputs
console.log(wrappedString.value);
console.log(wrappedNumber.value);
console.log(wrappedBoolean.value);
console.log(wrapInObject("Generic").value);
console.log(wrapInObject(100).value);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