Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 20, 2022 08:25 pm GMT

The Basics Of Typescript Classes

Introduction To Classes In Typescript

Before we start, we need to understand the basic concepts of Typescript. What are types in Typescript? How to set up the Typescript project? etc. If you're just a beginner you might have a hard time understanding these concepts. Here are some good resources to help you get started:

What you will learn in this article:

  • What are classes in Typescript?
  • Basic syntax of classes in Typescript
  • Data modifiers in classes
  • SubClasses in Typescript
  • Interfaces in Typescript classes

...and more!

Should you use classes instead of functions?

This is a question that is often asked in the community and it's hard to find a good answer. I personally think that classes are more flexible and easy to maintain, but they require some extra complexity to set up. I would use classes for more significant projects, but in smaller projects, functions are a good choice.

What is a Class?

Classes are like blueprints for objects. They are used to define the shape of an object and to create new objects. A class can have properties and methods. They are mainly used in object-oriented programming languages like C#, Java, and C++. You might have already used classes in JavaScript or other languages. Classes were introduced in ES6 (ECMAScript 2015) and are available in Typescript as well.

Basic Class Syntax and Usage

Now we can create a basic class called Animal. Classes in Typescript need to have some properties so that we can use them later. It takes three parameters name, age, and species as strings.

class Animal {  name: string;  age: number;  species: string;}

Now you probably have an error that the properties name, age, and species are not defined. This is because we haven't defined them yet. To define them, we need to create a constructor for our class to initialize the values. Constructors are special methods that are called when we create a new instance of our class. The constructor needs three arguments name, age, and species as strings.

class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {  }}

After that, we need to set the values of our properties. We can do this by using the this keyword.

class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;  }}

this keyword is used to set the values of our class's properties in the constructor.

After the class is created, we can create a new instance of it. We can do this by creating a new constant or variable called animal and assigning it to a new instance of our class. You can create new instances of our class by using the new keyword.

Then you need to pass in the same arguments that you passed in the constructor.

class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;  };};const animal = new Animal('Max', 4, 'dog');

Note: Constructors are called when you create a new instance of our class.

Now let's try to print out the values of our class.

class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;  };};const max = new Animal('Max', 4, 'dog');console.log(max);
Output:{ name: 'Max', age: 4, species: 'dog' }

You can also choose the value to print.

console.log(max.name);
Output:Max
console.log(max.age);
Output:4
console.log(max.species);
Output:dog

Data Modifiers in Classes

Data modifiers are used to define the access level of our class's properties. We can define our class's properties as public, private, or protected.

class Animal {  public name: string; // default access level.  private age: number; // private access level.  protected species: string; // protected access level.  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;  }}
  • public: This is the default access level. It means that the property can be accessed from anywhere within your code.
  • private: This means that the property can only be accessed from within the class.
  • protected: This means that the property can only be accessed from within the class and its subclasses. We will learn about subclasses in the next section.

Class inheritance (SubClasses)

Subclasses are used to extend the functionality of our classes. We can create a new class that extends (inherits) our existing class. Now we can create a subclass called Dog that inherits from the Animal class.

class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;  };};class Dog extends Animal { // `Dog` class inherits from `Animal` class.  breed: string; // `breed` property is defined in the `Dog` class.  constructor(name: string, age: number, species:string, breed: string) { // `Dog` class constructor.    super(name, age, species); // `super` keyword is used to call the constructor parameters of the parent class.    this.breed = breed; // `breed` property is set to the value of `breed` parameter.  }};

Let me explain what's happening here. Firstly, we create a new class called Dog that extends the Animal class. Then we create a constructor for Dog that calls the constructor of the Animal class. And then we add a new property breed to the Dog class.

Notice that we don't need to define the name, age, and species properties in the Dog class. This is because the Dog class inherits the name, age, and species property from the Animal class with the keyword super. This is a keyword that is used to call the constructor parameters of the parent class. We can use the super to get the value of the name, age, and species properties from the Animal class.

Now we can create a new instance of our Dog class.

const dog = new Dog('Max', 4, 'dog', 'Labrador');console.log(dog);
Output:{ name: 'Max', age: 4, species: 'dog', breed: 'Labrador' }

Class Heritage

Class heritage is used to implement interfaces to classes. We can create a new interface and implement it in our classes with the implements keyword.

interface Animal {  name: string;  age: number;  species: string;}class Animal implements Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;  }}

Other

How to use classes in other files

// index.tsexport class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;    console.log(`${this.name} is a ${this.age} year old ${this.species}`);  }}//Or:class Animal {/*Content*/};export default Animal;// animal.tsimport { Animal } from './index'; //You can import classes from other files.// orimport Animal from './index';const lucy = new Animal('Lucy', 1, 'dog', logInfo());
Output:Lucy is a 1 year old dog

Returning a value from a class

class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    this.name = name;    this.age = age;    this.species = species;  }  getName() {    return `Name is ${this.name}`;  }};const lucy = new Animal('Lucy', 1, 'dog');console.log(lucy.getName());
Output:Name is Lucy

Common errors

Expected (number) arguments, but got 0. (2554)

This is because we are trying to call the constructor of the Animal class with no parameters.

// Errorconst lucy = new Animal();// No errorsconst lucy = new Animal('Lucy', 1, 'dog');

Property '(property name)' has no initializer and is not definitely assigned in the constructor. (2564)

This is because we are trying to access the (property name) property of the Animal class.

// Error (Property 'name' has no initializer and is not definitely assigned in the constructor. (2564))class Animal {  name: string;  age: number;  species: string;  constructor(name: string, age: number, species: string) {    // (this.name = name;) is missing    this.age = age;    this.species = species;  }}// No errorsclass Animal {    name: string;    age: number;    species: string;    constructor(name: string, age: number, species: string) {        this.name = name;        this.age = age;        this.species = species;    }}

If you have any other weird errors, you can always double-check your code and if that does not work, google the issue. Google is your best friend.

Conclusion

Now you know the basics of classes in Typescript. There are many other things that you can do with classes, so you can go to the official documentation to learn more. You can find it here. You can always come back to this article if you forget something. I recommend using classes in your main or side projects. I hope you enjoyed the article!

Other resources


Original Link: https://dev.to/lukahietala/the-basics-of-typescript-classes-1kml

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To