|
| 1 | +# Classes and Interfaces |
| 2 | +In TypeScript, classes are similar to JavaScript, with some syntactic |
| 3 | +differences and more powerful features. In this module, we will examine classes and discuss interfaces, a |
| 4 | +concept of object-oriented programming that does not exist in JavaScript. |
| 5 | + |
| 6 | +This module assumes familiar with the basic ideas of classes and object-oriented |
| 7 | +programming. |
| 8 | + |
| 9 | +## Classes |
| 10 | + |
| 11 | +### Class members |
| 12 | +Let's take a look at a basic example of a class with some members. Class members will sometimes be referred to as fields or instance variables. |
| 13 | +These are all equivalent terminology. In this example, the members are `x`, `y`. |
| 14 | + |
| 15 | +```typescript |
| 16 | +class Point { |
| 17 | + x: number; |
| 18 | + y: number; |
| 19 | +} |
| 20 | + |
| 21 | +const pt = new Point(); |
| 22 | +pt.x = 0; |
| 23 | +pt.y = 0; |
| 24 | +``` |
| 25 | + |
| 26 | +### Field properties |
| 27 | +A field of a class can be one of the following: `public`, `private`, `protected`, or |
| 28 | +`readonly`. |
| 29 | + |
| 30 | +- `public`: This field can be read to and written as normal. |
| 31 | +- `private`: Only accessible by the instance of the class. For example, this |
| 32 | + variable cannot be accessed by any code other than the functions in the |
| 33 | + class. |
| 34 | +- `protected`: Similar to `private`, but subclasses can access the field. |
| 35 | +- `readonly`: This field can only be read, but it can never be assigned or have |
| 36 | + its value changed (similar to `const`). |
| 37 | + |
| 38 | +In general, it is considered good practice in coding to use the minimal visibility |
| 39 | +required. For example, if you never plan to write to the field, you should start |
| 40 | +with `readonly`. If you find that you need to write to the field, but only in |
| 41 | +the code in the class, you should use `private`. Usage of `protected` is |
| 42 | +rare. In most cases, well-structured code will have most instance variables of a |
| 43 | +class as `private`. |
| 44 | + |
| 45 | +Let's take a look at an example of a field with the `readonly` keyword: |
| 46 | +```typescript |
| 47 | +class File { |
| 48 | + readonly name: string = "untitled"; |
| 49 | + |
| 50 | + constructor(otherName?: string) { |
| 51 | + if (otherName !== undefined) { |
| 52 | + this.name = otherName; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + err() { |
| 57 | + this.name = "not ok, the field is readonly"; |
| 58 | + } |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +However, this will give you an error: |
| 63 | +``` |
| 64 | +Cannot assign to 'name' because it is a read-only property. |
| 65 | +``` |
| 66 | + |
| 67 | +And an example of a field with the `private` keyword, which disallows access |
| 68 | +from outside of the class. |
| 69 | +```typescript |
| 70 | +class Counter { |
| 71 | + private x = 0; |
| 72 | + |
| 73 | + increment() { |
| 74 | + // This is ok. |
| 75 | + x = x + 1; |
| 76 | + } |
| 77 | +} |
| 78 | +const ctr = new Counter(); |
| 79 | + |
| 80 | +// This code is outside of the class. It is not accessible. |
| 81 | +console.log(ctr.x); |
| 82 | +``` |
| 83 | + |
| 84 | +This code too, results in a useful error: |
| 85 | +``` |
| 86 | +Property 'x' is private and only accessible within class 'Counter'. |
| 87 | +``` |
| 88 | + |
| 89 | +### Static members |
| 90 | +In some cases, you want to keep information related to the class as a whole, |
| 91 | +regardless of a particular instance of a class. TypeScript, like JavaScript, |
| 92 | +provides the `static` keyword. these can also use the same modifiers such as |
| 93 | +`public`, `private`, etc. |
| 94 | + |
| 95 | +```typescript |
| 96 | +class StaticExample { |
| 97 | + static x = 0; |
| 98 | + static printStatic() { |
| 99 | + console.log(StaticExample.x); |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +console.log(StaticExample.x); |
| 104 | + |
| 105 | +// Notice how there is no instantiation with the `new` keyword. |
| 106 | +// We are simply accessing the value from the name of the class, |
| 107 | +// not an instance of the class. |
| 108 | +StaticExample.printStatic(); |
| 109 | +``` |
| 110 | + |
| 111 | +### Inheritance |
| 112 | + |
| 113 | +Like JavaScript, the `extends` keyword can be used to create a subclass of a |
| 114 | +class. |
| 115 | + |
| 116 | +```typescript |
| 117 | +class RecodedMember { |
| 118 | + getTitle() { |
| 119 | + return "Generic member"; |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +class RecodedStudent { |
| 124 | + getTitle() { |
| 125 | + return "Student"; |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +const member : RecodedMember = new RecodedMember(); |
| 130 | +console.log(member.getTitle()); // "Generic member" |
| 131 | + |
| 132 | +// Note how, because this is a subclass, we can also use the type of the parent |
| 133 | +// class here, if we would like. |
| 134 | +const student: RecodedMember = new RecodedStudent(); |
| 135 | +console.log(student.getTitle()); // "Student" |
| 136 | +``` |
| 137 | + |
| 138 | +## Interfaces |
| 139 | +TypeScript provides a powerful object-oriented concept called interfaces, using |
| 140 | +the `interface` keyword. In TypeScript, and interface represents the type of an |
| 141 | +object. In some other languages, an interface is similar to a class, but without |
| 142 | +its implementation. In TypeScript, it can also be used this way. |
| 143 | + |
| 144 | +You may have heard the word interface elsewhere. The term itself generically |
| 145 | +refers to something that we interact with. As a result, it makes sense, for |
| 146 | +example, to refer to the interface of an API. We see the interface of an API, |
| 147 | +but we do not know its implementation. We simply call the endpoints on the API; |
| 148 | +and a "clean interface" is one that hides its implementation from the user. |
| 149 | + |
| 150 | +This concept is more generally called [information |
| 151 | +hiding](https://en.wikipedia.org/wiki/Information_hiding), and it applies in |
| 152 | +many areas in computer programming. For example, |
| 153 | +at the levels of API design, where we talk about endpoints, and for classes, |
| 154 | +when we talk about concrete code. |
| 155 | + |
| 156 | +For further information, refer to the [official |
| 157 | +documentation](https://www.typescriptlang.org/docs/handbook/2/objects.html). |
| 158 | + |
| 159 | + |
| 160 | +### Object types |
| 161 | +In JavaScript and TypeScript, it is extremely common to organized and pass |
| 162 | +around data as objects. |
| 163 | + |
| 164 | +For example: |
| 165 | + |
| 166 | +```typescript |
| 167 | +// Takes a point, and returns a new point with its values increased by one. |
| 168 | +function shift(point: { x: number, y: number }): { x: number, y: number } { |
| 169 | + return { x: point.x + 1, y: point.y + 1 }; |
| 170 | +} |
| 171 | +``` |
| 172 | + |
| 173 | +But what if we have multiple functions that want to use such a type? Already in |
| 174 | +the above, we see that it's quite clunky to keep writing out this object type. In this |
| 175 | +case, interfaces come in handy. |
| 176 | + |
| 177 | +```typescript |
| 178 | +interface Point { |
| 179 | + x: number; |
| 180 | + y: number; |
| 181 | +} |
| 182 | + |
| 183 | +function shift(point: Point): Point { |
| 184 | + return { x: point.x + 1, y: point.y + 1 }; |
| 185 | +} |
| 186 | +``` |
| 187 | + |
| 188 | +You may also achieve the same thing using a type alias, or the `type` keyword. |
| 189 | +Note that when using the `type` keyword, an equals sign is required -- a slight |
| 190 | +syntactic difference. |
| 191 | +```typescript |
| 192 | +type Point = { |
| 193 | + x: number; |
| 194 | + y: number; |
| 195 | +} |
| 196 | + |
| 197 | +const origin: Point = { x: 0, y: 0 }; |
| 198 | +``` |
| 199 | + |
| 200 | +Similar to parameters, you can specify optional properties that may be |
| 201 | +undefined, using a `?`: |
| 202 | + |
| 203 | +```typescript |
| 204 | +type Point = { |
| 205 | + x: number; |
| 206 | + y: number; |
| 207 | + // This is an optional property. |
| 208 | + z?: number; |
| 209 | +} |
| 210 | +``` |
| 211 | +
|
| 212 | +### Extending interfaces |
| 213 | +The power of interfaces is that it defines a high-level idea of a set of fields |
| 214 | +or methods. Similar to classes and inheritance, interfaces can be extended in |
| 215 | +TypeScript. |
| 216 | +
|
| 217 | +```typescript |
| 218 | +interface Colorful { |
| 219 | + color: string; |
| 220 | +} |
| 221 | + |
| 222 | +interface Circle { |
| 223 | + radius: number; |
| 224 | +} |
| 225 | + |
| 226 | +interface ColorfulCircle extends Colorful, Circle {} |
| 227 | + |
| 228 | +const cc: ColorfulCircle = { |
| 229 | + color: "red", |
| 230 | + radius: 42, |
| 231 | +}; |
| 232 | +``` |
| 233 | + |
| 234 | +In the example above, we have two iterfaces: `Colorful` and `Circle`. If we want |
| 235 | +a `ColorfulCircle`, we do not need to rewrite the fields; instead, we can reuse |
| 236 | +the two interfaces, combining them using the `extends` keyword. |
| 237 | + |
| 238 | +## Further reading |
| 239 | +This module covers much of the syntax available for classes in TypeScript. |
| 240 | +However, there are also many other quality-of-life features available that can |
| 241 | +be found in the [official |
| 242 | +documentation](https://www.typescriptlang.org/docs/handbook/2/classes.html) for |
| 243 | +classes. |
0 commit comments