TypeScript - Getting Started Guide
UPDATE : Based on TypeScript 2.1.4
TypeScript is the superset of ECMA2015 (ES6), which is the superset of ES5. TypeScript is transcompiled to Javascript before loading in web page.
Installation
TypeScript can be installed using
npm
> npm install -g typescript
Test Example
Create a file example.ts
Now transcompile your TypeScript code to Javascript by giving the command
> tsc example.ts
This will generate a the Javascript equivalent of it.
Here in this example any TypeScript feature is not used. So both the scripts will be the same.
Features
TypeScript inherits all the features of Javascript. So to start coding in TypeScript, you are advised to learn ES6 first. Here, let us explore the exclusive features of TypeScript.
Data Types
As the name denotes, TypeScript is Javascript with Data Types. But it is optional. When declaring a variable data type of that variable can be specified there.
The data types available in TypeScript are listed below.
- Number : Standard floating point value, expressed as decimal, hexadecimal, octal and binary literals.
- String : Text content, enclosed in single quotes or double quotes and in grave accents if it is a template
- Boolean : True/False
- Array : Indexed collection of items
- Tuple : A fixed length array
- Enum : Set of items
- Any : Any type value. Used when type of data is not known
- Void : Denotes having no type
See the examples below
Just like void, there are some other special purpose data types
- Null :
null
type - Undefined :
undefined
type - Never : Represents a value that will never be received
See the examples below
Typed Functions
Data Types can be used in functions also. See the examples below
in an object
with arrow syntax
Interfaces
Data Types do not exist in Javascript. When TypeScript is transcompiled to Javascript, type-checking is executed on the code by the TypeScript transcompiler. Even if there are data type errors, the process will generate a Javascript file that can be executed. So here Data Type is just a ‘contract’ between two code segments. It is the responsibility of the developer to make sure that he is not breaking the norms of the ‘contract’ anywhere. Interfaces can be used to enforce Data Type validation and Structure validation in the interaction between code segments.
A simple example is given below.
Here
member: { name:string, age:number, place:string }
is the structure defined for the parameter to call the function createMember
. This is the point where interface
comes into picture. This structure can be defined as an interface
as shown belowAppend a
?
to the property name if it is optional.See the property
place?
in the example given below.Similarly interface can be defined for functions. See the example below.
Find more examples of
interface
here