5
votes

I am new to angular 2 and studying Typescript in order to build simple apps in angular 2.

And I found that we can use classes, interfaces, modules etc with typescript to build applications.

But as far as I studied javascript I know that javascript doesn't support classes, interfaces, modules etc.

Below shown are some of the concepts which I encountered while my study.

Interfaces

Interfaces are used to type-check whether an object fits a certain structure. By defining an interface we can name a specific combination of variables, making sure that they will always go together.

"When translated to JavaScript, interfaces disappear - their only purpose is to help in the development stage." In the below example we define a simple interface to type-check a function's arguments:

enter image description here

"The order of the properties does NOT matter. We just need the required properties to be present and to be the right type. If something is missing, has the wrong type, or is named differently, the compiler will warn us."

enter image description here

Classes

When building large scale apps, the object-oriented style of programming is preferred by many developers.

TypeScript offers a class system, including inheritance, abstract classes, interface implementations, setters/getters, and etc."

Here is a class

enter image description here

Modules

A module can export any number of functions, classes or variables. By default, the objects are exported with their original names. We can change this if required. A module can have a default exported member as well.

Following snippet shows examples of different export statements:

enter image description here

As typescript is being compiled down to javascript how are these classes, interfaces, modules etc are being transpired?

1
You will find a lot of information in the documentation of typescript: typescriptlang.org/docs/handbook/classes.html - Dinistro
Additionally you can take a look at some compiled typescript files to see, what exactly happens, but for this you need to understand the object inheritance of JS: developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/… - Dinistro
Please @Dinistro, make an answer out of that so that I can upvote it. RTFM ! - user4676340
I'd also recommend typing some of your examples into the TypeScript playground - it will show you in real time what the compiled output of your code is. - Joe Clay
ok i will try this out - Heena

1 Answers

1
votes

Please Read The Fine Manual, starting e.g. with https://www.typescriptlang.org/docs/handbook/interfaces.html

Also, write a small v1.ts source file, compile it, and read the resulting JS output code. Then add a small edit to create v2.ts, compile it, and use /usr/bin/diff -u to notice what changed between the v1 & v2 output.