Dieses Blog durchsuchen

Sonntag, 31. Juli 2016

typescript: create first typesave javascript functions, interfaces and classes

If you want to program typesafe javascript,  you can use microsofts "typescript". Its a so called "superset ontop of javascript" to extend it for serveral things like:

- interfaces
- abstract classes
and types

Typescript can do that for you. Sounds nice, but in real life there are some problems,

You cant use typescript in the browser, because most of the browser doesnt support it. So you need to compile typescript into plain javascript, wich then can be included or required like any other script.

So you need a compiler. You can use node.js and his packagemanager to install typescript and its compiler. Further you can use gulp or broccoli to compile the ts to javascript.

We want to use node.js on ubuntu. Windows and Mac users installations are similiar to that.

1) install node.js
apt-get install nodejs

ln -s /usr/bin/nodejs /usr/bin/node


2) install npm
apt-get install npm

3) install typescript globaly on your machine
npm install -g typescript


I suggest to use an IDE with typescript support.
In my case I have used Microsofts VS Code. Its platformindependend and has a lot of plugins.


To install it on linux you can use my last post:
magento2-tuts.blogspot.de/2016/07/vs-code-microsoft-editor-on-ubuntu-1604.html

In the plugin manager of vscode type "typescript" in the searchfield and install at least one of the plugins.

Lets start coding:
Create a file named "myFirstTypeSafeFunction.ts" and write following ts code

As you can see we have created a function named myFirstTyoeSafeFunction() with a parameter person from type string.

Thats great, because in javascript this typehinting from type string would cause an error.

At next we have to compile the .ts file into a .js file.

Switch to your terminal in the folder where you have saved your .ts file and type:
tsc myFirstTypeSafeFunction.ts

After that a file myFirstTypeSafeFunction.js was generated with the javascript code to the .ts code.


Lets create an Interface in typescript. 

 
this is really cool. So now you are able to write some kind of better oop code in javascript by using interfaces.


At next we want to use the interface in a class construct.

Lets setup a class implementing an interface in javascript.
Thats awsome, isnt it. As you can see, you can simply pass an object from type IHuman to a constructor of a class, like in PHP , Java, C# or other Type based language. If you want to see, what Microsoft is making of yout typescript, you can open the corresponding .js files an have a look in the generated code, At the end typescript will help you writing better javascript code.

Keine Kommentare:

Kommentar veröffentlichen