Building the User Model#

User.ts#

A user can open any number of questions and answers, but can only choose an answer for a question that they've opened. The User class will keep track of a user's opened questions and answers but will not keep track of which questions have a chosen answer (that information will live within each Question object). The diagram below shows the relationship between User and the other entities in our program:

User Class Diagram

Notice we have a circular dependency chain between Question, Answer, and User. As we'll see when we implement our classes, this is a circular type dependency as opposed to a circular runtime dependency (which would require more care to implement). We'll cover this later, but for now let's trust that the code will work as expected. To avoid import errors, let's create two empty classes for Question and Answer in their respective files:

We set the export types to any to avoid compile-time errors while we're developing these classes, although this means we should be extra cautious of producing runtime errors. Using our empty classes, we create our initial User implementation:

In the constructor, we initialize the questions and answers properties to empty arrays. As a user opens questions and answers, we will modify these properties.

Adding Questions and Answers#

Adding questions and answers is fairly straight forward: we push items into the corresponding array using Array.prototype.push():

Adding a question/answer mutates the underlying array, but we have the flexibility of creating new arrays or using an entirely different data structure because we do not expose these properties to the outside world. The arrays are an implementation detail of the class and we are free to refactor as we please. For example, if we were to create a hasAnswer() method that iterates over each answer looking for a specific ID, we might consider refactoring the code to use Map or Set for a more performant way of finding answers (assuming our class had a huge number of answers to iterate to justify making this change).

 

This page is a preview of Beginners Guide to TypeScript

Please select a discussion on the left.