Class handling in TypeScript

Tram Ho

Class and Inteface are two powerful constructs not only in object-oriented programming but also type-checking in TypeScript. From a Class we can create Objects with the same method structure and properties. An Interface is a group of inter-method properties that describe an Object but do not implement or initialize them.

Class and Interface are both used to define the structural components of an Object, in TypeScript both can be used. Deciding whether to use Class or Interface actually depends on our case.

Use TypeScript Class

We can use class as an Object. A Class defines how an Object looks, acts and instantiates a Class and methods. We get an Object that has the functions and actions that the properties have been determined.

  1. Oke now take a look and have a class ShippingInfo definition below.

ShippingInfo is a simple Class that initializes an Object with properties such as driverInfo driverDeviceId invoiceNo invoiceNo .

  1. Now how do we use the ShippingInfo class?

We simply create an Object with new ShippingInfo means that now that you have initialized a shipInfo Object with all the properties, in action of ShippingInfo we temporarily treat shipInfo as a copy of ShippingInfo .

  1. And wondering what should I do if I want to initialize the value of the shipInfo Object?

Once you have created new ShippingInfo() now you want to initialize the shipInfo you just need to:

So we’ve started a value for Object shipInfo you can initialize the properties less ShippingInfo but will not be initialized but attributes that ShippingInfo no.

So now there is a case where the api data returns too much if we assign each attribute like that ??? Oh no, we just need to perform data checking and reassign them to finish !!!

My example here is the data the server returns to you so how do you assign it to ShippingInfo .

So now that the data returned from the server has been assigned to the shippingInfo class, you can now use the shippingInfo Object anywhere to load the data into the view.

  1. Now we want to intervene to change the data the server returns, what to do?

So your data has been changed using the class then we can easily perform the data handling actions we want.

  1. What if we want to add the “shipper name” attribute to Object ShippingInfo ?

And now you have a ShippingInfoEx class that inherits from ShippingInfo and has a deliverName property

Share the news now

Source : Viblo