TypeScript Classes [Typescript Tutorial]

The following is a simple TypeScript class defined.

With TypeScript, unlike native JavaScript, there is a native class keyword. The following snippet illustrates a simple TypesScript class definition:

Unlike the native JavaScript, TypeScript has a native class keyword. A public member, fullname and a public constructor that acquire three arguments: first, middle and last name. Through that constructor, the arguments are assembled to combine it to the public fullname member.

JavaScript’s compiler looks different:

The equivalent JavaScript is a bit more wordy. The example code creates Person object with four public members: firstname, middlename, lastname and fullname. But with TypeScript, it may be simplified to:

As you can see TypeScripts code is more articulate than JavaScript. It goes well with the compiler catching errors that would otherwise caught only at runtime.

TypeScript Interface

TypeScript’s interface concept doesn’t exist in JavaScript. A dynamic, untyped fuctional language is what JavaScript is. In an interface, a contract is specified and that will not go well with language like JavaScript. But it doesn’t mean that JS doesn’t support the concept of classes, interfaces or strong typing and it also doesn’t mean that you write this way purposely as if not wanting to enforce such features.

Again with our Person class, let’s include a simple interface:

IPerson is created as the interface. It has a single public member named fullname. See the function displayPerson is bound to IPerson interface as a single argument. Whenever your code referred to any property in Person argument instead of publicly exposed IPerson interface, TypeScript compiler returns an error. Let’s modify displayPerson function to display a first name as an example.

Here’s the sample error: e as an example

typescript classes

The compiler enforce the specified contacts in the interface.

Also, variables created based on interfaces can be created just like in C#: var myPerson : IPerson;

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.