What a class is
A class is a blueprint for objects. It says which data each object carries, called its properties, and which actions it can perform, called its methods. An object made from the class is an instance. The class Employee describes what any employee has, such as a name and an age, while one instance is the actual employee named Andrew who is 30.
Use a class when you have several values that belong together and you want to create many objects with the same shape. In TypeScript a class also gives you a type: once Employee exists, you can write Employee as the type of a variable.
Declaring a class
You declare a class with the class keyword. Unlike plain JavaScript, TypeScript wants every property listed in the class body with its type, before the constructor assigns it:
class Employee {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
Three parts are involved:
- Property declarations,
name: string;andage: number;, tell the compiler which properties every instance has. - The constructor is a special method named
constructor. It runs once when an object is created and sets up its properties. Its parameters have type annotations, like those of any function. thisrefers to the object being created or used. Inside the constructor,this.nameis the property, and plainnameis the parameter. The linethis.name = namecopies the parameter into the property.
If you leave out the property declaration, the compiler reports "Property 'name' does not exist on type 'Employee'" at the assignment.
Creating objects and using them
The new keyword creates an instance and runs the constructor with the arguments you give. Properties are read and changed with the dot operator:
let emp: Employee = new Employee("Andrew", 30);
console.log(emp.name); // Andrew
emp.age = 40;
console.log(emp.age); // 40
The annotation : Employee is optional, because TypeScript infers the type from new Employee(...). The compiler also checks the call. new Employee("Andrew") is rejected because an argument is missing, and new Employee(5, 30) is rejected because 5 is not a string.
Each instance has its own copy of the properties. Changing one employee's age doesn't touch any other employee.
Methods
Methods are functions that belong to the class. They are written without the function keyword, with their parameter types and a return type. void means the method returns nothing:
class Employee {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
printName(): void {
console.log(this.name);
}
printEmployee(): void {
this.printName();
console.log(this.age);
}
}
let emp1 = new Employee("Andrew", 30);
emp1.printEmployee(); // prints Andrew, then 30
let emp2 = new Employee("Mary", 25);
emp2.printEmployee(); // prints Mary, then 25
A method uses the object it was called on through this. That is why the first call prints Andrew and 30 and the second prints Mary and 25: the code is the same, but this is a different object. To call another method of the same object, or to read a property, you must write this. in front. Without it, the name refers to a variable outside the class and isn't found, and the compiler reports "Cannot find name".
Gotchas
- Annotations check, they don't convert. Types are erased when TypeScript is compiled to JavaScript. The constructor's
name: stringstops you from writing a wrong call in your own code, but at run time nothing verifies the argument. If a number sneaks in through a cast or untyped data, it is stored as a number. - A compile error doesn't stop the program. In these lessons, the compiler reports a type error but still produces the JavaScript, which runs. Read the compiler's messages as warnings you must fix.
- Methods lose
thiswhen detached. Afterconst f = emp1.printEmployee;, callingf()fails with "Cannot read properties of undefined", because there is no object before the dot any more. Call methods on the object:emp1.printEmployee(). - Forgetting
new. Calling a class like a plain function,Employee("Andrew", 30), is an error. A class can only be created withnew. - Shorthand. Writing
constructor(public title: string) {}declares the property and assigns it in one go. This lesson spells it out in full so each step is visible.
The lesson's exercise: a Job class
The exercise builds a small class, step by step.
- Declare the class named
Joband list one property in its body:title, of typestring. - Add the constructor with a parameter named
titleof typestring, so each new object receives its job title. - Store the parameter. Inside the constructor, assign it to
this.title. The left side is the property of the object, and the right side is the parameter. - Add the method
hireMebelow the constructor, with return typevoid, since it prints and returns nothing. - Print the message in
hireMe: join"You're hired as a "andthis.titlewith+and pass the result toconsole.log. A baretitlethere would not compile. - Create the object. Below the class, declare
jobwithlet, annotated asJob, and set it tonew Job("Software Engineer"). - Call the method with
job.hireMe().
class Job {
title: string;
constructor(title: string) {
this.title = title;
}
hireMe(): void {
console.log("You're hired as a " + this.title);
}
}
let job: Job = new Job("Software Engineer");
job.hireMe();
Running it prints You're hired as a Software Engineer. The string "You're hired as a " ends with a space, which is what separates the words from the title. Because the text contains an apostrophe, it is written in double quotes.
Key takeaways
- A class is a blueprint, and
newcreates an instance from it. - In TypeScript, declare each property with its type in the class body, then assign it in the constructor.
- Inside the class, use
thisto reach the object's own properties and methods. - Methods are declared without
function, with typed parameters and a return type such asvoid. - Types are checked by the compiler and erased afterwards, so they don't change what the program does at run time.