To create a generic interface in TypeScript, we can use the interface
keyword followed by the name of the interface and a set of angled brackets containing one or more type parameters. For example, we can create a Stack
interface with a generic T
parameter representing the type of elements in the stack:
index.ts95 chars6 lines
In this example, the Stack
interface specifies three methods: push
to add an item of type T
to the stack, pop
to remove and return the top item from the stack, and size
to return the number of items in the stack. The T
type parameter can be replaced with any type when using this interface.
We can also use generic types in combination with classes. For example, we can create a LinkedList
class with a generic T
parameter representing the type of data stored in the list nodes:
index.ts505 chars24 lines
In this example, the LinkedListNode
class represents a node in the linked list with a data
property of type T
and a next
property pointing to the next node in the list. The LinkedList
class then uses this LinkedListNode
class to construct a linked list data structure with append
method to add new nodes to the end of the list.
Using generic types and interfaces can make our code more reusable and flexible, allowing us to write functions and classes that can work with different types of data.
gistlibby LogSnag