var message:string = "Welcome to Free Time Learning"
console.log(message)
.ts
extension and then compiled into JavaScript using the compiler. You can write the file in any code editor and the compiler needs to be installed on your platform. After the installation, the command tsc <filename>.ts
compiles the TypeScript code into a plain JavaScript file.SN | JavaScript | TypeScript |
---|---|---|
1 | It was developed by Netscape in 1995. | It was developed by Anders Hejlsberg in 2012. |
2 | JavaScript source file is in ".js" extension. | TypeScript source file is in ".ts" extension. |
3 | JavaScript doesn't support ES6. | TypeScript supports ES6. |
4 | It doesn't support strongly typed or static typing. | It supports strongly typed or static typing feature. |
5 | It is just a scripting language. | It supports object-oriented programming concept like classes, interfaces, inheritance, generics, etc. |
6 | JavaScript has no optional parameter feature. | TypeScript has optional parameter feature. |
7 | It is interpreted language that's why it highlighted the errors at runtime. | It compiles the code and highlighted errors during the development time. |
8 | JavaScript doesn't support modules. | TypeScript gives support for modules. |
9 | In this, number, string are the objects. | In this, number, string are the interface. |
10 | JavaScript doesn't support generics. | TypeScript supports generics. |
$ npm install -g typescript
.msi
installer for the node.node -v
" to check if the installation was successful.$ npm
install -g typescript
.js
” to “.ts
”, your TypeScript file is ready. To compile any .ts
file into .js
use the following command :tsc <TypeScript File Name>
freetimelearn.ts
”freetimelearn.js
tsc -- outFile comman.js file1.ts file2.ts file3.ts
.ts
” file and output into a single “comman.js
” file.tsc --outFile file1.ts file2.ts file3.ts
file2.ts
and file3.ts
will be compiled and the output will be placed in file1.ts
. So now your file1.ts
contains JavaScript code.let identifier: number = value;
let identifier: string = " ";
let identifier: bool = Boolean value;
let num: number = null;
let num: number = undefined;
let unusable: void = undefined;
var [identifier] : [type-annotation] = value; //Declaring type and value in a single statement
var [identifier] : [type-annotation]; //Declaring type without value
var [identifier] = value; //Declaring its value without type
var [identifier]; //Declaring without value and type
let values: number[] = [];
values[0] = 10;
values[1] = 20;
values[2] = 30;
let values: number[] = [15, 20, 25, 30];
let values: Array<number> = [15, 20, 25, 30];
let person: any = "Foo";
// json may come from a third-party API
const employeeData: string = `{"name": "Ramana", "salary": 90000}`;
// parse JSON to build employee object
const employee: any = JSON.parse(employeeData);
console.log(employee.name);
console.log(employee.salary);
function notify(): void {
alert("The user has been notified.");
}
interface interface_name {
// variables' declaration
// methods' declaration
}
class Student {
studCode: number;
studName: string;
constructor(code: number, name: string) {
this.studName = name;
this.studCode = code;
}
getGrade() : string {
return "A+" ;
}
}​
module module_name{
class xyz{
export sum(x, y){
return x+y;
}
} ​
We can divide the module into two categories :module Sum {
export function add(a, b) {
console.log("Sum: " +(a+b));
}
} ​
External Module : External modules are also known as a module. When the applications consisting of hundreds of files, then it is almost impossible to handle these files without a modular approach. External Module is used to specify the load dependencies between the multiple external js files. If the application has only one js file, the external module is not relevant. ECMAScript 2015(ES6) module system treats every file as a module.
export class MyClass {
}
export var x:MyClass instance = new MyClass();
namespace <namespace_name> {
export interface I1 { }
export class c1{ }
let foo: unknown = "Chanti";
let bar: string = foo; // Type 'unknown' is not assignable to type 'string'.(2322)
let foo: unknown = "Chanti";
let bar: string = foo as string;
let pt: { x: number; y: number } = {
x: 10,
y: 20
};
?
’ after the property name. let pt: { x: number; y: number; z?: number } = {
x: 10,
y: 20
};
console.log(pt);
z
’ is marked as optional, the compiler won’t complain if we don’t provide it during the initialization.console.log(null == null); // true
console.log(undefined == undefined); // true
console.log(null == undefined); // true, with type-conversion
console.log(null === undefined); // false, without type-conversion
console.log(0 == undefined); // false
console.log('' == undefined); // false
console.log(false == undefined); // false
enum Team {
Alpha,
Beta,
Gamma,
Delta
}
let t: Team = Team.Delta;
enum Author {
Anders = "Anders",
Hejlsberg = "Hejlsberg"
};
console.log(typeof 10); // "number"
console.log(typeof 'foo'); // "string"
console.log(typeof false); // "boolean"
console.log(typeof bar); // "undefined"
let greeting = "hello";
let typeOfGreeting: typeof greeting; // similar to let typeOfGreeting: string
…
’ syntax and indicates that the function can accept one or more arguments.function add(...values: number[]) {
let sum = 0;
values.forEach(val => sum += val);
return sum;
}
const sum = add(5, 10, 15, 20);
console.log(sum); // 50
const first = [1, 2, 3];
const second = [4, 5, 6];
first.push(...second);
console.log(first); // [1, 2, 3, 4, 5, 6]
function multiply({ a, b, c }: { a: number; b: number; c: number }) {
console.log(a * b * c);
}
multiply({ a: 1, b: 2, c: 3 });
You can simplify the above code by using an interface or a named type, as follows:
type ABC = { a: number; b: number; c: number };
function multiply({ a, b, c }: ABC) {
console.log(a * b * c);
}
multiply({ a: 1, b: 2, c: 3 });
tsconfig.json
file in a directory marks that directory as the root of a TypeScript project. It provides the compiler options to compile the project.tsconfig.json
file :{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
<
) and close (>
) brackets which makes it strongly typed collections. It uses a special kind of type variable <T>
that denotes types.function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("edureka");
let output2 = identity<number>( 117 );
console.log(output1);
console.log(output2);
C#
and Java
. The typecasting comes with runtime support whereas type assertion has no impact on runtime. However, type assertions are used purely by the compiler and provide hints to the compiler on how we want our code to be analyzed.let empCode: any = 007;
let employeeCode = <number> code;
console.log(typeof(employeeCode)); //Output: number
…
’)before the parameter. It allows the functions to have a variable number of arguments without using the arguments object. It is very useful where we have an undetermined number of parameters. function sum(a: number, ...b: number[]): number {
let result = a;
for (var i = 0; i < b.length; i++) {
result += b[i];
}
console.log(result);
}
let result1 = sum(2, 4);
let result2 = sum(2,4,6,8);
if (x == null) {
} ​
If we use a strict-check, it will always true for values set to null and won't evaluate as true for undefined variables.var a: number;
var b: number = null;
function check(x, name) {
if (x == null) {
console.log(name + ' == null');
}
if (x === null) {
console.log(name + ' === null');
}
if (typeof x === 'undefined') {
console.log(name + ' is undefined');
}
}
check(a, 'a');
check(b, 'b');​
"a == null"
"a is undefined"
"b == null"
"b === null"
<type>
) conflicted with JSX.let empCode: any = 111;
let employeeCode = code as number;​
When using TypeScript with JSX, only as-style assertions are allowed.let myAdd = function(x: number, y: number): number {
return a+b;
};
console.log(myAdd())
class NewPrinter extends Printer {
doPrint(): any {
super.doPrint();
console.log("Called Child class.");
}
doInkJetPrint(): any {
console.log("Called doInkJetPrint().");
}
}
let printer: new () => NewPrinter;
printer.doPrint();
printer.doInkJetPrint();
var tuple_name = [value c,value b,value c,…value n]
var yourtuple = [12,"Hi"];
class Sprite {
name = "";
x = 0;
y = 0;
constructor(name: string) {
this.name = name;
}
}
T extends U ? X : Y
Interface | Type |
It’s a form of syntax. | It’s a form of a collection of data types. |
Provides a way to define the entities. | It supports the creation of a new name for a type. |
Comparatively includes more capabilities than Type. | Comparatively includes fewer capabilities than Interface. |
Can use multiple merged declarations | Cannot use multiple merged declarations |
Two interfaces having the same name get merged. | Two interfaces having the same name get merged. |
|
') symbol.(type1 | type2 | type3 | .. | typeN)
let myVar : string | number; //Variable with union type declaration
myVar = 256; //OK
myVar = 'Maddy'; //OK
myVar = true; //Error - boolean not allowed
/, ./
or ../.
import Entry from "./components/Entry";
import { DefaultHeaders } from "../constants/http";
import * as $ from "jquery";
import { Component } from "@angular/core";
/// <reference path="..." />
/// <reference no-default-lib="true"/>
let sum = (a: number, b: number): number => {
return a + b;
}
console.log(sum(20, 30)); //returns 50
(a + b)
is the body of the function and (a: number, b: number) are inline parameters.