Introducing Classes
You can think of a classes as defining a template of functionality. That’s the “data and functions” part. At runtime, we create instances of classes and we normally call them “objects.” We often think in terms of “passing messages” or “invoking functions” on objects[^1].
Developers use classes to model people, places, business entities and concepts - all kinds of things. Here’s a simple example that begins to model a bus that might be used for public transportation:
Use the keyword followed by the name of the class.
Public transportation authorities typically assign route numbers to busses. The Bus
class models the route number in a private
field called .
Our business rules dictate that busses must know how to “say” their name. A function, SayRoute
, meets the requirement by listing the bus’s route number out to the console.
TypeScript introduces a bit of new lingo to describe classes[^2]:
- myRouteNumber is a property.
- SayRoute is a method.
Classes do nothing by themselves. They are much like cookie cutter templates - you can tell what the cookie is going to look like but you have no cookie until you have cookie dough. We create new objects as shown:
The above code declares two instances of the object, “myBeloved148” (a super express) and “theDreaded164” (a super local). It then invokes the SayRoute
method on each instance.
You no doubt noticed a complimentary pair of descriptors, and public
. The Bus class declares a private member, myRouteNumber. Private members (i.e. properties and methods) may only be referenced or invoked within the object itself. Public members and methods may be referenced both within the class itself, but also by client code. This means that the following code will not compile:
As with every other part of the language, good TypeScript IDEs provide intellisense to help you locate and use public and private methods properly. Here’s a short video demonstrating that point:
(If you can’t see the video, try accessing it here or type this URL into your web browser: ).
TypeScript classes go much deeper than this. The next chapter takes that dive.
[^2]: It’s probably more accurate to say that it borrows the lingo from other languages.