Generic Interfaces
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 61 of 73.
Just as you can create generic functions, you can also create generic interfaces. This allows you to define the shape of an object while keeping certain property types flexible and reusable.
Here's how you create a generic interface using the same type parameter syntax:
interface Container {
value: T;
isEmpty: boolean;
}The <T> after the interface name creates a type parameter that can be used throughout the interface definition. In this example, the value property will have whatever type you specify when using the interface, while isEmpty remains a fixed boolean type.
When you use a generic interface, you specify the concrete type in angle brackets:
const stringContainer: Container = {
value: "hello",
isEmpty: false
};
const numberContainer: Container = {
value: 42,
isEmpty: false
};This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a generic interface named Result that can hold data of any type along with success information.
The interface should have two properties:
successof typebooleandataof typeT(the generic type parameter)
Create the following objects using your generic interface:
stringResultof typeResult<string>withsuccess: trueanddata: "Operation completed"numberResultof typeResult<number>withsuccess: trueanddata: 42booleanResultof typeResult<boolean>withsuccess: falseanddata: falsearrayResultof typeResult<string[]>withsuccess: trueanddata: ["item1", "item2", "item3"]
Create a generic function named processResult that:
- Uses a generic type parameter
T - Takes one parameter
resultof typeResult<T> - Returns a string message
- If
successistrue, returns"Success: [data]" - If
successisfalse, returns"Failed: [data]"
Print the following outputs:
- Print the result of calling
processResultwithstringResult - Print the result of calling
processResultwithnumberResult - Print the result of calling
processResultwithbooleanResult - Print the result of calling
processResultwitharrayResult - Print
stringResult.data
Cheat sheet
Generic interfaces allow you to define the shape of an object while keeping certain property types flexible and reusable.
Create a generic interface using type parameter syntax:
interface Container<T> {
value: T;
isEmpty: boolean;
}The <T> after the interface name creates a type parameter that can be used throughout the interface definition.
Use a generic interface by specifying the concrete type in angle brackets:
const stringContainer: Container<string> = {
value: "hello",
isEmpty: false
};
const numberContainer: Container<number> = {
value: 42,
isEmpty: false
};Try it yourself
// TODO: Write your code here
// Create the generic Result interface
// Create the objects using the Result interface
// Create the generic processResult function
// Print the required outputsThis 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