A class is a blueprint for objects. It has properties, which hold data, and methods, which do things. New creates an object from the class. And this means, the current object.
Items is a private array of titles, starting empty. Add pushes a title into it. Count is a getter, so we read it like a property, without brackets. We create a basket, and add two books. Run it. The basket has two books.
main.tstypescript
class Basket { private items: string[] = []; add(title: string) { this.items.push(title); } get count(): number { return this.items.length; }}const basket = new Basket();basket.add("Dune");basket.add("Emma");console.log(`Books in the basket: ${basket.count}`);
Items is private, so only code inside the class may touch it. Here, we try to empty it from outside. Run it. TypeScript stops us. Items is private, and only accessible within class Basket.
main.tstypescript
class Basket { private items: string[] = []; add(title: string) { this.items.push(title); } get count(): number { return this.items.length; }}const basket = new Basket();basket.add("Dune");basket.add("Emma");console.log(`Books in the basket: ${basket.count}`);basket.items = [];
Output
main.ts(17,8): error TS2341: Property 'items' is private and only accessible within
class 'Basket'.
Writing public, or private, in front of a constructor parameter creates a property, and fills it, in one go. Angular code uses this style a lot. Title is public, so we can read it. And the private price is used inside price for. Run it. Dune, and the price for three copies.
main.tstypescript
class Book { constructor(public title: string, private price: number) {} priceFor(copies: number): number { return this.price * copies; }}const dune = new Book("Dune", 9.99);console.log(dune.title);console.log(dune.priceFor(3).toFixed(2));
Classes have properties, methods, and getters, and private keeps data safe inside. Constructor parameters can create properties. Next, optional, and union types.