Tuesday 25 April 2017

TypeScript : JavaScript Feature Gap

Building your first TypeScript file

In your editor, type the following JavaScript code in greeter.ts:
function greeter(person) {
    return "Hello, " + person;
}

var user = "Syafiq Zahir";

document.body.innerHTML = greeter(user);

Compiling your code

We used a .ts extension, but this code is just JavaScript. You could have copy/pasted this straight out of an existing JavaScript app.
At the command line, run the TypeScript compiler:
tsc greeter.ts
The result will be a file greeter.js which contains the same JavaScript that you fed in.
Now we can start taking advantage of some of the new tools TypeScript offers. Add a : string type annotation to the ‘person’ function argument as shown here:
function greeter(person: string) {
    return "Hello, " + person;
}

var user = "Syafiq Zahir";

document.body.innerHTML = greeter(user);

Type annotations

Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. In this case, we intend the greeter function to be called with a single string parameter. We can try changing the call greeter to pass an array instead:

No comments:

Post a Comment