TypeScript is a strongly typed programming language that builds on
JavaScript, giving you better tooling at any scale.
What is TypeScript?
TypeScript adds additional syntax to JavaScript to support a tighter
integration with your editor.
TypeScript code converts to JavaScript, which runs anywhere
JavaScript runs
TypeScript understands JavaScript and uses type inference to give
you great tooling without additional code.
TypeScript - Variable
let employeeName:string = "John";
const num:number = 100;
TypeScript Data Type - Number
let first:number = 123; // number
let second: number = 0x37CF; // hexadecimal
let third:number=0o377 ; // octal
let fourth: number = 0b111001;// binary
TypeScript - String
let employeeName:string = "John Smith";
let employeeDept:string = "Finance";
// Pre-ES6
let employeeDesc1: string = employeeName + " works in the "
+ employeeDept + " department.";
TypeScript Data Type - Boolean
let isPresent:boolean = true;
let isPresent:boolean = false;
TypeScript - Arrays
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
let fruits: Array = ['Apple', 'Orange', 'Banana'];
TypeScript - Tuples
var employee: [number, string] = [1, "Steve"];
var person: [number, string, boolean] = [1, "Steve", true];
var user: [number, string, boolean, number];// declare tuple variable
user = [1, "Steve", true, 20, "Admin"];// initialize tuple variable
TypeScript Data Type - Enum
enum PrintMedia {
Newspaper,
Newsletter,
Magazine,
Book
}
enum PrintMedia {
Newspaper = 1,
Newsletter,
Magazine,
Book
}
enum PrintMedia {
Newspaper = 1,
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3,
Book = 10
}
TypeScript - Union
let code: (string | number);
code = 123; // OK
code = "ABC"; // OK
code = false; // Compiler Error
let empId: string | number;
empId = 111; // OK
empId = "E111"; // OK
empId = true; // Compiler Error
TypeScript Data Type - Any
let something: any = "Hello World!";
something = 23;
something = true;
TypeScript Data Type - Void
function sayHi(): void {
console.log('Hi!')
}
let speech: void = sayHi();
console.log(speech); //Output: undefined
TypeScript Data Type - Never
function throwError(errorMsg: string): never {
throw new Error(errorMsg);
}
function keepProcessing(): never {
while (true) {
console.log('I always does something and never ends.')
}
}
TypeScript - Functions
Named Functions
function Sum(x: number, y: number) : number {
return x + y;
}
Sum(2,3); // returns 5
Anonymous Function
let Sum = function(x: number, y: number) : number
{
return x + y;
}
Sum(2,3); // returns 5
TypeScript - Interfaces
interface IEmployee {
empCode: number;
empName: string;
getSalary: (number) => number; // arrow function
getManagerName(number): string;
}
TypeScript - Interfaces
Interface as Type
interface KeyPair {
key: number;
value: string;
}
let kv1: KeyPair = { key:1, value:"Steve" }; // OK
let kv2: KeyPair = { key:1, val:"Steve" };
// Compiler Error: 'val' doesn't exist in type 'KeyPair'
let kv3: KeyPair = { key:1, value:100 }; // Compiler Error:
Interface as Function Type
interface KeyValueProcessor { (key: number, value: string): void; };
function addKeyValue(key:number, value:string):void {
console.log('addKeyValue: key = ' + key + ', value = ' + value)
}
function updateKeyValue(key: number, value:string):void {
console.log('updateKeyValue: key = '+ key + ', value = ' + value)
}
let kvp: KeyValueProcessor = addKeyValue;
kvp(1, 'Bill'); //Output: addKeyValue: key = 1, value = Bill
kvp = updateKeyValue;
kvp(2, 'Steve'); //Output: updateKeyValue: key = 2, value = Steve
Interface for Array Type
interface NumList {
[index:number]:number
}
let numArr: NumList = [1, 2, 3];
numArr[0];
numArr[1];
interface IStringList {
[index:string]:string
}
let strArr : IStringList = {};
strArr["TS"] = "TypeScript";
strArr["JS"] = "JavaScript";
Optional Property
interface IEmployee {
empCode: number;
empName: string;
empDept?:string;
}
let empObj1:IEmployee = { // OK
empCode:1,
empName:"Steve"
}
let empObj2:IEmployee = { // OK
empCode:1,
empName:"Bill",
empDept:"IT"
}
Read only Properties
interface Citizen {
name: string;
readonly SSN: number;
}
let personObj: Citizen = { SSN: 110555444, name: 'James Bond' }
personObj.name = 'Steve Smith'; // OK
personObj.SSN = '333666888'; // Compiler Error
Extending Interfaces
interface IPerson {
name: string;
gender: string;
}
interface IEmployee extends IPerson {
empCode: number;
}
let empObj:IEmployee = {
empCode:1,
name:"Bill",
gender:"Male"
}
TypeScript - Data Modifiers
public
class Employee {
public empCode: string;
empName: string;
}
let emp = new Employee();
emp.empCode = 123;
emp.empName = "Swati";
private
class Employee {
private empCode: number;
empName: string;
}
let emp = new Employee();
emp.empCode = 123; // Compiler Error
emp.empName = "Swati";//OK
protected
class Employee {
public empName: string;
protected empCode: number;
constructor(name: string, code: number){
this.empName = name;
this.empCode = code;
}}
class SalesEmployee extends Employee{
private department: string;
constructor(name: string, code: number, department: string) {
super(name, code);
this.department = department;
}}
let emp = new SalesEmployee("John Smith", 123, "Sales");
empObj.empCode; //Compiler Error
TypeScript - ReadOnly
class Employee {
readonly empCode: number;
empName: string;
constructor(code: number, name: string) {
this.empCode = code;
this.empName = name;
}
}
let emp = new Employee(10, "John");
emp.empCode = 20; //Compiler Error
emp.empName = 'Bill';
TypeScript - Static
class Circle {
static pi: number = 3.14;
static calculateArea(radius:number) {
return this.pi * radius * radius;
}
}
Circle.pi; // returns 3.14
Circle.calculateArea(5); // returns 78.5
TypeScript - Generics
function getArray(items : T[] ) : T[] {
return new Array().concat(items);
}
let myNumArr = getArray([100, 200, 300]);
let myStrArr = getArray(["Hello", "World"]);
myNumArr.push(400); // OK
myStrArr.push("Hello TypeScript"); // OK
myNumArr.push("Hi"); // Compiler Error
myStrArr.push(500); // Compiler Error
Multiple Type Variables
function displayType(id:T, name:U): void {
console.log(typeof(id) + ", " + typeof(name));
}
displayType(1, "Steve"); // number, string
Methods and Properties of Generic Type
function displayType(id:T, name:U): void {
id.toString(); // OK
name.toString(); // OK
id.toFixed(); // Compiler Error: 'toFixed'
//does not exists on type 'T'
name.toUpperCase(); // Compiler Error: 'toUpperCase'
//does not exists on type 'U'
console.log(typeof(id) + ", " + typeof(name));
Generic Constraints
class Person {
firstName: string;
lastName: string;
constructor(fname:string, lname:string) {
this.firstName = fname;
this.lastName = lname;
}
}
function display(per: T): void {
console.log(`${ per.firstName} ${per.lastName}` );
}
var per = new Person("Bill", "Gates");
display(per); //Output: Bill Gates
display("Bill Gates");//Compiler Error
TypeScript - Generic Interface
interface IProcessor
{
result:T;
process(a: T, b: T) => T;
}
Example: Generic Interface as Type
interface KeyPair {
key: T;
value: U;
}
let kv1: KeyPair = { key:1, value:"Steve" }; // OK
let kv2: KeyPair = { key:1, value:12345 }; // OK
Example: Generic Interface as Function Type
interface KeyValueProcessor
{
(key: T, val: U): void;
};
function processNumKeyPairs(key:number, value:number):void {
console.log('processNumKeyPairs: key = ' + key + ', value = ' + value)
}
function processStringKeyPairs(key: number, value:string):void {
console.log('processStringKeyPairs: key = '+ key + ', value = ' + value)
}
let numKVProcessor: KeyValueProcessor = processNumKeyPairs;
numKVProcessor(1, 12345); //Output: processNumKeyPairs: key = 1, value = 12345
let strKVProcessor: KeyValueProcessor = processStringKeyPairs;
strKVProcessor(1, "Bill"); //Output: processStringKeyPairs: key = 1, value = Bill
Example: Generic Interface as Function Type
interface IKeyValueProcessor
{
process(key: T, val: U): void;
};
class kvProcessor implements IKeyValueProcessor
{
process(key:number, val:string):void {
console.log(`Key = ${key}, val = ${val}`);
}
}
let proc: IKeyValueProcessor = new kvProcessor();
proc.process(1, 'Bill'); //Output: processKeyPairs: key = 1,
// value = Bill
TypeScript - Generic Classes
class KeyValuePair
{
private key: T;
private val: U;
setKeyValue(key: T, val: U): void {
this.key = key;
this.val = val;
}
display():void {
console.log(`Key = ${this.key}, val = ${this.val}`);
}
}
let kvp1 = new KeyValuePair();
kvp1.setKeyValue(1, "Steve");
kvp1.display(); //Output: Key = 1, Val = Steve
let kvp2 = new KayValuePair();
kvp2.SetKeyValue("CEO", "Bill");
kvp2.display(); //Output: Key = CEO, Val = Bill
Example: Generic Class implements Generic Interface
interface IKeyValueProcessor
{
process(key: T, val: U): void;
};
class kvProcessor implements IKeyValueProcessor
{
process(key:T, val:U):void {
console.log(`Key = ${key}, val = ${val}`);
}
}
let proc: IKeyValueProcessor = new kvProcessor();
proc.process(1, 'Bill'); //Output: key = 1, value = Bill
Thank you for your attention.