Welcome to an exciting exploration of TypeScript classes, where we delve into constructors and class methods. Imagine building a robot: Constructors establish its initial state, and class methods instruct it to perform tasks. Ready to deepen your understanding? Let’s get started!
A TypeScript class serves as a blueprint for creating objects and incorporates static typing for both properties and methods. Here's a basic class, Robot
, with type annotations:
TypeScript1class Robot { 2 // Class definition 3} 4 5const robotInstance = new Robot();
Initially, this Robot
class is an empty shell. To make it functional, we need to define properties with explicit types, as well as methods.
A constructor
is a unique method in TypeScript that sets up an object when an instance is created. You'll use the constructor
keyword to define it, and it is automatically invoked during the instance creation process. If no constructor is explicitly defined, TypeScript provides a default constructor, allowing instance creation without initializing specific properties. By using static typing within the constructor, as shown in the code block, you ensure that the parameters have specified types, which aids in maintaining consistency and reducing errors when initializing object properties.
Here, we enhance the Robot
class by adding a constructor
:
TypeScript1class Robot { 2 name: string; 3 color: string; 4 5 constructor(name: string, color: string) { 6 this.name = name; 7 this.color = color; 8 } 9} 10 11const robotInstance = new Robot("Robbie", "red");
In this case, the constructor
method gets automatically called when we create a new Robot
instance, set with name
and color
attributes. When creating an instance of Robot, the constructor initializes properties in the order they are defined in the constructor.
While TypeScript does not support multiple constructors, you can attain flexibility using default parameters, where a parameter is given a default value if no value or undefined
is provided. Type annotations play a crucial role here, guaranteeing that parameters have defined types, even when default values are utilized.
Here's a default color for our robots:
TypeScript1class Robot { 2 name: string; 3 color: string; 4 5 constructor(name: string, color: string = 'grey') { 6 this.name = name; 7 this.color = color; 8 } 9} 10 11const robotInstance = new Robot("Robbie", "red"); 12const robotInstance2 = new Robot("Bobby");
With default parameters, the color becomes optional, defaulting to grey
if not provided, maintaining type safety. As a result, the robot instance Bobby
is assigned the color grey
by default.
Class methods in TypeScript allow objects to perform actions. Annotating method parameters and return types reinforces type safety. This reduces the risk of runtime errors and makes the code more predictable and easier to maintain:
TypeScript1class Robot { 2 name: string; 3 color: string; 4 5 constructor(name: string, color: string = 'grey') { 6 this.name = name; 7 this.color = color; 8 } 9 10 sayHello(): void { 11 console.log(`Hello, I am ${this.name} and I am ${this.color}.`); 12 } 13} 14 15const robotInstance = new Robot("Robbie", "red"); 16robotInstance.sayHello();
Here, the sayHello
method enables our robot instance to interact using specified types.
Methods allow the modification and retrieval of class instance attributes. While you can access attributes directly in the provided example, as the attributes are public, using setter and getter methods can enhance safety by providing controlled access and validation. Type annotations ensure type consistency, further safeguarding data integrity.
TypeScript1class Robot { 2 name: string; 3 color: string; 4 5 constructor(name: string, color: string = 'grey') { 6 this.name = name; 7 this.color = color; 8 } 9 10 sayHello(): void { 11 console.log(`Hello, I am ${this.name} and I am ${this.color}.`); 12 } 13 14 setName(newName: string): void { 15 this.name = newName; 16 } 17 18 getName(): string { 19 return this.name; 20 } 21 22 setColor(newColor: string): void { 23 this.color = newColor; 24 } 25 26 getColor(): string { 27 return this.color; 28 } 29 30 changeAttributes(newName: string, newColor: string): void { 31 this.name = newName; 32 this.color = newColor; 33 } 34 35 greetPerson(personName: string): void { 36 console.log(`Hello ${personName}, I am ${this.name}!`); 37 } 38} 39 40const robotInstance = new Robot("Robbie", "red"); 41robotInstance.sayHello(); 42 43robotInstance.setName("Bobby"); 44robotInstance.setColor("blue"); 45robotInstance.sayHello(); 46 47console.log(robotInstance.getName()); 48console.log(robotInstance.getColor()); 49 50robotInstance.changeAttributes("Charlie", "green"); 51robotInstance.sayHello(); 52 53robotInstance.greetPerson("Alice");
The setName
and setColor
methods allow changing the name and color of the robot after it has been created. The getName
and getColor
methods enable retrieving these values when needed.
Well done! You've explored TypeScript classes, constructors, and class methods, emphasizing the importance of static typing through type annotations. This approach enhances code reliability and readability, allowing for more nuanced control over your classes. Moving forward, you'll have the skills needed to infuse more sophistication into your TypeScript projects, making them both robust and versatile. Let's continue to rebuild our coding toolbox with practical exercises in the upcoming lessons!