Let’s learn TypeScript – Lesson 1

Thanks to Javascript modern webpages are more interactive, more useful and more helpful – but JavaScript is not scripted Java …

JavaScript does no have strong typing – is this advantage or disadvantage? It depends …

For someone JS gives more freedom and faster way to code simple objects or arrays. It’s very nice for small apps, but after some time and many written apps we can miss restricted typing, code completion or smart refactoring in our favourite IDE.

I tried to fix problem with code completion by writing JSdocs – I’m familiar with Symfony 2 and PHPdocs – so I’m not scared of this solution. It works – but we all know how using comments can end – with a lot of extra block of outdated text disturbing reading code.

InteliJ have a very nice tool for JS refactoring – but I think that that Java refactoring tool in this IDE is awesome. The problem is it lacks strong typing.

I heard about Dart, firstly I was very sceptical but after some time I learned Angular.js and I felt that I really need restricted typing in JS – less errors and more productivity.

I know that maintaining large single page app is possible in JavaScript – sure, but who has time for it?

I really look forward for ATScript and Angular 2.0 – now we know that Angular 2.0 is being written in TypeScript.

According to the official webapge of TypeScript:

TypeScript lets you write JavaScript the way you really want to.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
Any browser. Any host. Any OS. Open Source.

www.typescriptlang.org

 

TypeScript Support in InteliJ 14.1.3

InteliJ has a very nice suport for TypeScript with live compiling to JS:

type-script-intelij-1

JS file is compiled in time of writing the code – we can preview compiled JS file anytime.

We also have a live preview of what goes wrong:

How to enable it? See: https://www.jetbrains.com/idea/help/typescript-support.html

Online Editor

If you don’t have ItelliJ – you can always try your skills in Playground – simple TypeScript online editor provided by Microsoft: http://www.typescriptlang.org/Playground

 

Hello world example

With anonymous function

 

With named function

 

ok – we have named function but let’s add info about return value:

 

lets add our first typed argument:

 

ok we get an error – because we didn’t provide a name, let’s fix it:

 

now it’s better. Let’s take alert() out of function

 

Let’s add some if condition with returning number:

 

we need to change return declaration to any because we can return string or number

 

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *