Generics

TypeScript supports a programming construct called generics. TypeScript generics allow you to write code that operates against broad swathes of classes and interfaces without giving up strong typing. You write your code to execute against types (classes and interfaces), as opposed specific, concrete classes. Once written, you access this generic code by providing a concrete type at runtime. Let’s consider an example.

Imagine that you are developing a game and storing and retrieving game information to/from a database. This means you have to implement the classic Create, Read, Update and Delete operations (CRUD) for the various objects in the game. Here’s some high level code that beings to implement the game and this logic:

  1. class Game {
  2. private _gameState: any;
  3. public CurrentPlayerIndex: number;
  4. public Players: Player[];
  5. constructor(initialGameState: any) { this._gameState = initialGameState;}
  6. }
  7. class Player {
  8. private _playerState: any;
  9. public PlayerName: string;
  10. public PlayerScore: number;
  11. constructor(initialPlayerState: any) { this._playerState = initialPlayerState; }
  12. }
  13. class GameStateDBHelper {
  14. public CreateNewGame(): Game {
  15. // Initialize a new Game object and save it to the back end database.
  16. // Return the empty game.
  17. return new Game(null);
  18. }
  19. public LoadGame(query: string): Game {
  20. // Use supplied query to load some game state from the database.
  21. // Convert that to a GameState object
  22. // return it
  23. return new Game(null);
  24. }
  25. public SaveGame(gameToSave: Game): boolean {
  26. // Marshall game state and save it to the back end database.
  27. return true; // indicates successful save
  28. }
  29. public DeleteGame(gameToDelete: Game): boolean {
  30. // Issue database command to delete game state.
  31. return true; // indicates successful deletion
  32. }
  33. }
  34. const gameHelper = new GameStateDBHelper();
  35. const newGame = gameHelper.CreateNewGame();
  36. const oldGame = gameHelper.LoadGame("a database query");
  37. const didSaveGame = gameHelper.SaveGame(oldGame);
  38. const didDeleteGame = gameHelper.DeleteGame(newGame);

The code defines three classes:

  • Game: This is the game object itself, keeping track of overall game state, including a list of players and the currently active player.
  • Player: Represents a player in the game. Players also have some state information, although its different than a Game.
  • GameStateDBHelper: A utility class that provides input/output operations and supports all four CRUD operations for the Game object.

GameStateDBHelper defines four public methods, one for each of the CRUD operations. These each take commonsense input parameters and return commonsense results. Consider LoadGame:

  1. public LoadGame(query: string): Game {
  2. // Use supplied query to load some game state from the database.
  3. // Convert that to a GameState object
  4. // return it
  5. return new Game(null);
  6. }

LoadGame is passed a query (think “select * from Games…”). It parses the result and returns back a new Game object. Obviously, there’s a lot of hand waving going on in the example, but hopefully the concept is clear.

The DB helper object makes it easy to execute the CRUD operations as needed:

  1. const gameHelper = new GameStateDBHelper();
  2. const newGame = gameHelper.CreateNewGame();
  3. const oldGame = gameHelper.LoadGame("a database query");
  4. const didSaveGame = gameHelper.SaveGame(oldGame);
  5. const didDeleteGame = gameHelper.DeleteGame(newGame);

Despite the clarity and strong-typed goodness, this approach is nonetheless problematic. We already know we’ll want another database-backed entity - Player. If we simply follow the current approach, we end up creating a new helper function, PlayerStateDBHelper. It has to provide the same CRUD functions and each one shaped almost identically to GameState. “Shape” in this case means:

  • Looking up database connection information.
  • Accessing the database
  • Executing some common command that varies only in small details from one object to another
  • Managing errors
  • Returning success/fail messages

We can mitigate most of that using TypeScript’s generic functionality. Here’s how it would look like:

  1. interface DBBackedEntity {
  2. TableName: string;
  3. }
  4. class GameState implements DBBackedEntity {
  5. private myDBTableName: string;
  6. public get TableName(): string { return this.myDBTableName; }
  7. public CurrentPlayerIndex: number;
  8. public AllPlayers: GamePlayer[];
  9. constructor(someGameState: any) {
  10. this.myDBTableName = "Games";
  11. }
  12. }
  13. class GamePlayer implements DBBackedEntity {
  14. private myDBTableName: string;
  15. public get TableName(): string { return this.myDBTableName; }
  16. public PlayerName: string;
  17. public Score: number;
  18. constructor(somePlayerState: any) {
  19. this.myDBTableName = "Players";
  20. }
  21. }
  22. class DBHelper<T extends DBBackedEntity> {
  23. public CreateRecord() : T { return null; }
  24. public ReadRecord(query: any): T { return null; }
  25. public DeleteRecord(basedOn: T): boolean { return true; }
  26. public UpdateRecord(basedOn: T) : boolean { return true; }
  27. }
  28. const gameStateHelper = new DBHelper<GameState>();
  29. const gamePlayerHelper = new DBHelper<GamePlayer>();
  30. const newPlayer = gamePlayerHelper.CreateRecord();
  31. console.log(`New player score: ${newPlayer.Score}.`)
  32. const existingGameState = gameStateHelper.ReadRecord("some query goes here");
  33. const newGameState = gameStateHelper.CreateRecord();
  34. const deleteResult = gameStateHelper.DeleteRecord(newGameState);
  35. const updateResult = gameStateHelper.UpdateRecord(existingGameState);

Generics introduce some new syntax and leverage existing concepts (like interfaces) in new ways.

The code first defines a new interface, DBBackedEntity. This interface requires a single text field, “TableName”. This obviously maps to a database table via its name.

It then creates two models for the Game and its Players respectively. Each of them implements the DBBackedEntity interface and assigns a database table name via the object’s constructor.

The DBHelper class introduces the generics syntax:

  1. class DBHelper<T extends DBBackedEntity> {
  2. public CreateRecord() : T { return null; }
  3. public ReadRecord(query: any): T { return null; }
  4. public DeleteRecord(basedOn: T): boolean { return true; }
  5. public UpdateRecord(basedOn: T) : boolean { return true; }
  6. }

This syntax, <T extends DBBackedEntity> effectively says, “The DB helper class works against any type (class) that implements the DBBackedEntity interface.” When client code instantiates an instance of DBHelper, it will specify a value for that parameter, T. These two lines show how to pass a value for T:

  1. const gameStateHelper = new DBHelper<GameState>();
  2. const gamePlayerHelper = new DBHelper<GamePlayer>();

When working with generics, we supply type parameters via angle brackets: DBHelper<GameState> and DBHelper<GamePlayer>. TypeScript replaces the T parameter in the DBHelper class with GameState and GamePlayer respectively.

Further Reading

Summary

This chapter on generics brings the main body of of Yet Another TypeScript Book to a close. The next chapter suggests some additional reading and videos that you may find of interest