javascript tutorial - [Solved-3 Solutions] Typescript - javascript - java script - javascript array



Problem:

What is Typescript and why would I use it in place of JavaScript ?

Solution 1:

superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

Solution 2:

here's some TypeScript (we can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  
click below button to copy the code. By JavaScript tutorial team

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

click below button to copy the code. By JavaScript tutorial team

Solution 3:

the TypeScript compiler can determine through control flow based type analysis whether or not your code can safely use a variable or not. In other words when you check a variable is undefined through for example an if statement the TypeScript compiler will infer that the type in that branch of your code's control flow is not anymore nullable and therefore can safely be used. Here is a simple example:

let x : number?;
if (x !== undefined) x += 1; // this line will compile, because x is checked.
x += 1; // this line will fail compilation, because x might be undefined.
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Typescript