What is TypeScript
Look at the below code
for (var i = 0; i < 10; i++) { /* … */}
console.log(i);
What will be the output? For some it will be “undefined” and for others, it will be 10.
Because of the way JavaScript was designed it does not throw an exception for the above code and that not the only problem with JS.
“undefined is not a function”, Mis-use to “this” Keyword, Difference between == & === are some of the idiocies which plague JS.
JavaScript is not a traditional language and because of that anyone working in languages like C#, Java does have to change their thought process. With ECMA Script 6 JavaScript has tried to add new features that would bring it closer to the traditional programming languages but as most us would be aware that having all the browsers support for ES6 features is not happening any time soon.
So, what’s the alternative to that time?
TypeScript:
It is a typed superset of JavaScript that compiles to plain JavaScript (typescriptlang.org). TypeScript compiles into pure JavaScript, every JavaScript program is also a TypeScript program.
Bottom Line: It is syntactic sugar for JavaScript, a very effective sugar
TypeScript provides features that are familiar to us like Interfaces, Classes, Inheritance, variable scoping, Data Types, and even generics. Using these features we can write a client-side code that looks very similar to the OO programming languages.
The best part because teams are already comfortable in languages like C# and Java learning curve for is very less. TypeScript is just not for places where you were using plain old Javascript but can help you in projects where you are using frameworks like Angular, Backbone.
Code:
TypeScript
|
JavaScript
|
class Student {
private firstName: string;
private lastName: string;
constructor(firstName: string, lastName: string
)
{
this.firstName = firstName;
this.lastName = lastName;
}
getFullName = function(salutation: string): string {
return (salutation + ‘ ‘ + this.lastName + ‘,‘
+ this.firstName);
}
window.onload = function () {
var peter = new Student(‘Homer’, ‘Simpson’);
}
|
var Student = (function () {
function Student(firstName, lastName) {
this.getFullName = function (salutation) {
return (salutation + ‘ ‘ + this.lastName + ‘,‘
+ this.firstName);
};
this.onload = function () {
var peter = new Student(‘Homer’, ‘Simpson’);
};
this.firstName = firstName;
this.lastName = lastName;
}
return Student;
})();
|
Post a Comment