The good TS

(TypeScript)

Shota Papiashvili

 @shotapa     

@shotap     

shota@walla.net.il     

What is TS?

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open source.

Site: https://www.typescriptlang.org/

 

  install:                                            compile:

 

npm install -g typescript
tsc script.ts

Why TS?

  1. Why not? every JS is by definition TS
  2. Lightweight and fast
  3. Dosent influence runtime
  4. Can find problems in your current JS code
  5. We all know the types (string, number, etc...)
  6. Another layer of testing our code
  7. ES6

Basics

// primitives
var a: number;
let b: string;
let c: boolean;
let d: any; // the same as var d;

// arrays
let e: number[];
let f: any[];
let g: (number | string)[];

// classes
let h: Email;
let i: Email[];
// primitives
var a;
var b;
var c;
var d; // the same as var d;

// arrays
var e;
var f;
var g;

// classes
var h;
var i;

The code in TS is more declarative! we can understand better and share code easily

Functions

function getFullName (firstName: string, lastName: string): string {
    return firstName + ' ' + lastName;
}

function that gets 2 string params and returns st

let x = 1; // if we give an inital value its like we decalured the type
x = getFullName('Shota', 'Papiashvili'); // ERROR!!!
let y = getFullName('Shota', 1); // Error!!!
function getFullName(getName: () => string): string {
    return 'Mr ' + getName();
}

function that gets as param a function that should return a string and this function returns string

Interface and Classes

interface IHuman {
    firstName: string;
    lastName: string;
    age: number;
    jobTitle?: string; // ? means optional
    walk(distance: number): boolean; // function
}

function getName(human: IHuman): string{
    return human.firstName + ' ' + human.lastName;
}

Interface and Classes

class Human {
	firstName: string;
	lastName: string;
	
	constructor (firstName: string, lastName: string){
		this.firstName = firstName;
		this.lastName = lastName;
	}
	
	walk(distance: number){
		console.log(distance + ' was long');
	}
}

class Student extends Human {
	school: string;
	
	getSchool(): string{
		return this.school;
	}
}

ES6

ES6 is built in!!!!

var name = 'Shota';
var hello = `Hello ${name}`;


var a = 1, b = 2;
[a, b] = [b, a];


var squers = [1, 2, 3].map( x => x * x );

The good TS (TypeScript)

By Walla Code

The good TS (TypeScript)

  • 661