In this article, let's learn how to install and setup Visual Studio 2012 to work with TypeScript,
TypeScript is a language extension language to JavaScript and adds object-oriented and some features to JavaScript. These features are:
- Type Annotations and Compile-Time Type Checking
- Classes
- Interface
- Modules
- Lambda Function
Type Annotations and Compile-Time Type Checking
TypeScript provides static typing through type annotations to enable type checking at compile time. This is optional and can be ignored to use the regular dynamic typing of JavaScript. The type annotations for the primitive types are number, bool and string.
- function Add(left: number, right: number): number {
- return left + right;
- }
Classes
TypeScript supports classes that are closely aligned with those proposed for ECMAScript 6, and includes extensions for instance and static member declarations and properties declared and initialized from constructor parameters. Classes and objects make TypeScript a modern JavaScript extension and makes OOP programmers to understand and write JS.
- class student {
- private fname: string;
- private age: number;
- constructor(fname: string, age: number) {
- this.fname = fname;
- this.age = age;
- }
- toString(): string {
- return this.fname + " (" + this.age + ")";
- }
- }
Interface
Interfaces provide the ability to give names to object types and the ability to compose existing named object types into new ones. Interfaces have no run-time representation; they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions.
Interface syntax:
- interface Identifier InterfaceExtendsClauseopt ObjectType
- InterfaceExtendsClause:
- extends InterfaceNameList
- InterfaceNameList:
- InterfaceName
- InterfaceNameList , InterfaceName
- InterfaceName:
- TypeName
Modules
A module is a body of statements and declarations that create and initialize a singleton module instance. Members exported from a module become properties on the module instance. The body of a module corresponds to a function that is executed once, thereby providing a mechanism for maintaining local state with assured isolation.
Module declaration:
- module IdentifierPathopt { ModuleBody }
- IdentifierPath:
- Identifier
- IdentifierPath . Identifier
- ModuleBody:
- ModuleElements
TypeScript supports two types of modules.
Internal modules: Internal modules are declared using ModuleDeclarations that specify their name and body. A named path with more than one identifier is equivalent to a series of nested internal module declarations.
External modules: An external module is written as a separate source file that contains at least one import or export declaration.