Class basics
- TypeScript course
- Intermediate
- Lesson 1/89
- 4 min
Learn to define classes in TypeScript.
What is a class?
A class is a blueprint for objects that share structure and behavior. Fields are variables defined inside the class; under strict mode they must have an initial value. You create a new instance with new.
class Person {
name: string = "";
age: number = 0;
}
const p = new Person();
p.name = "Ada";
console.log(p.name);Fields
Class fields are defined with just a name and a type, without let or const. Under strict mode an initial value is required. After creating an instance, you access fields with a dot and assign values.
class Point {
x: number = 0;
y: number = 0;
}
const pt = new Point();
pt.x = 3;
pt.y = 4;Practice Write a Car class
Define a Car class with make: string = "" and model: string = "" fields. Create a new Car instance, set make to "Toyota" and model to "Corolla", and print the make field.
Starter code
// Car sınıfı tanımla (marka ve model alanları, başlangıç değeri ver)
// yeni bir Car örneği oluştur
// alanları ayarla ve make'i yazdırSample solution
class Car {
make: string = "";
model: string = "";
}
const car = new Car();
car.make = "Toyota";
car.model = "Corolla";
console.log(car.make);Expected output
Toyota
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword is used to create an object from a class?
- create
- make
- instance
- new Correct answer
Explanation: The new keyword creates a new instance from a class. create, make, and instance are not valid TypeScript keywords.
2 Complete the class definition
____ Dog {
name: string = "";
}
class Dog {
name: string = "";
}
Explanation: To define a class you use the class keyword. interface defines an interface (cannot be instantiated with new), and type and function are invalid in this context.
3 Class basic parts
| Term | Meaning |
|---|---|
class |
Class definition keyword |
new Person() |
Create a new instance |
name: string |
Class field |
p.name |
Field access |