Hello and welcome to another exciting course in your learning journey! Today, we'll be delving into a core concept of Object-Oriented Programming (OOP): TypeScript classes. These classes act as templates, permitting us to craft objects — instances of these templates — each with unique attributes and behaviors. The objective of this lesson is to understand what classes are, how to create them, and their role within TypeScript coding.
A TypeScript class can be considered a construction blueprint. By adhering to this blueprint, we can create objects with specific structures, each holding variable values.
Here, Fruit is our blueprint or class. This blueprint enables us to generate an array of fruit objects, each with distinctive characteristics, resembling the construction of a building.
Creating an instance of a class — essentially animating an object from a blueprint — involves the new keyword:
In this case, apple is a specific instance or object of our Fruit class, much like a single building erected from a common blueprint.
To give our class some actions, we add methods — actions that objects created from the class can perform. We will look at two methods within our Fruit class: printColor and printMessage.
The first method, printColor, is a straightforward function that when called, prints Red to the console. This method doesn't take any parameters and its purpose is to showcase the color of the fruit.
The second method, printMessage, takes one parameter of type string — name. It uses this parameter to personalize a message, thus illustrating how methods can interact with data passed to them. When called, it prints a message in the format "Do you want a fruit, [name]?", where [name] is replaced with the actual string argument provided during the method call.
Notice that we've omitted the function keyword in both cases — that's a part of the TypeScript class syntax.
