You are on page 1of 13

npm install –g typescript

*to install Typescript compiler and more (is a superset programming lang of Javascript)

tsc –v

*check its version

tsc file-name.ts

*to compile a Typescript file

npm init

*to enable us install third-party packages & their dependencies into our project

npm install --save-dev lite-server

*to install lite server so that we don’t need to reload page for every change on ts file (but we still
compile the file)

Now go to created package json and in scripts write “start”:”lite-server” the new added package

Then run:

npm start

*to start the lite-server

Overview

Types

Next-gen js features (compiled for older browsers)

Non-js features like interface or generics

Meta-programming feats like decorators

Rich configuration options

Modern tooling that helps even in non-Typescript projects

Course outline

Typescript basics
Compiler & configuration deep dive

Working with next-gen js code

Classes and interface

--------------------------------

Advanced Types and Typescript features

Generics

Decorators

Time to practice – full projects

----------------------------

Working with namespaces and modules

Webpack & Typescript

Third-party libraries & Typescript

React + typescript & Nodejs + Typescript

Types
Core syntax and feats.

number (1, 5.3, -10)

string (`Hi`)

boolean (true, false)

add(n1: number, n2: number){ return n1 + n2 }

let n1: number; ou const n1 = 5;

*declare the default values of assignments

object ({name: “Me”, age: 20})

const person: {key1: type1; key2: type2;} = {key: val1, key2:val2} ou const per: {} = {assignments} ou
const person: object = {assignments}
array[1, 2, 3]

let hobbies: *string[]; hobbies = [“Água”, “Pão”]; ou let hobbies: any[]; hobbies = [“Ág”, 1, true]

for (const varName of array/obj.array){varName in code;}

*to iterate an array

Tuple [amount prefixed array]

const role: [type1, type2…]

enum Custom-name { ADMIN = *7, ANYROLE = *200… }

const role: Custom-name.ANYROLE

*enum to create a custom type. They receive numbers by default from 0 on or you can assign to them
(other data types or mix).

any *

*any type of data, no specification

let flowers = any; ou let games = any[]

Att: is not so coherent to Typescript objective

Union Types with |

let character: number | string | array[] | …

*allows it to receive the desired types at a time

Types alias

type Alias-name = type ou one-of-the-above-types;

let name: Alias-name;

function sum(n1: number, n2: number): number{return n1+n2}

*to declare the return type of a function


function sum(name: string): void{console.log(name)}

*to declare the non-returning type of a function

Undefined

Function

let sum: Function;

Sum = add;

ou

let sum: (assigned params if u need) => type of return

*declare that a var receives a specific type of function, its params and return type

Unknown

let you: unknown;

*is a bit restrictive than “any”

Never

function errorHandler(msg: string, code: number): never{

throw {message: msg, code: code}

*declares that a function never returns anything

Compiler & configuration deep dive


tsc app-name.ts –watch ou w

*compiles when you save file. For single files

Ctrl + c

*get out this mode


Ou

tsc (--w)*

*to all ts files in the dir (in watch mode)*

tsc --init

*all files in this directory’ll be compiled once saved. For many files

In tsconfig.json file:

, “exclude”: [“*.extension.ts”, node_modules]

*to prevent directories or files to compile

, “include”: [“”]

*to indicate directories or files to compile

, “files”: []

*only for files to compile

, “sourceMap”: true

*for debugging easiness, in the browser

, “outDir”: “./pathName” normally dist folder is the one for the output, and src for our ts files

*in which dir our compiled js result files get stored

, “removeComments”: true

*remove coms from ts files, so get ‘em smaller

, “noEmit”: true

*to not generate js files when ts ones are compiled

“noEmitOnError”: true

*to not gererate js files when ts ones are compiled with errors

Working with next-gen js code


Classes and interface
Class Name{

nameID: number;

nameLocal: string;

constructor (let person: string, let local: string){

this.nameLocal = local;

}//Serves to initialize the objects of the class

*create a class. Not all class needs a constructor

Generics
Creates reusable components in Typescript. Which makes ts. apps adaptable and scalable over time.

function identity <Type>(arg: Type): Type{

return args;}

let id = identity<number>(5) ou <number>(5) => number = identity;

*a generic function that deals with the type and not the values of fnctions and their params.

class GenericNum <NumType> {

zeroValue: NumType;

add: (x: NumType, y: NumType) => NumType;

Let myGen = new GenericNum<NumType> ();

myGen.zeroValue = 0;

myGen.add = function(x, y){return x + y;}


*a generic class

Typescript with React


After installing Typescript conpiler run this:

npx create-react-app

*create necessary modules and folder structure for react app

The files are saved as .tsx (‘cuz of jsx).

Typescript with Nodejs


Used to serve js files

node file.js

*to run js files with nodejs

Typescript with Expressjs


Used to create pop-ups

Advanced Types and Typescript features


Types assertion is a typecast

let someValue: unknown = “This is a string”;

let strnlength = (someValue as string).length; ou let strnkength = (<string>someValue).length;

*for typecasting with as-syntax or angle-bracket

function move(pet: Bird | Fish){

if(“swim” in pet){

return pet.swim();

} return pet.fly();}

*in operator. StringLiteral in unionType


interface ListItem {

[prop: string]: string | number;

const List: ListItem = {

name: "joyous jackal”;

email: "joyous@jackal.com";

age: 21;

*to use index types

In lock file, in dependency management, we set:

“dependencies”: {

“@typescript/lib-dom”:”npm:@types/web”}}

…name: arrayType

*rest params in functions

interface IComplexType{

id: number;

name?: string;//to turn it optional parameter

let complexType = IComplexType = {id: 4, name: “Futa”};

*mechanism to determine what properties, methods, and objects must implement. Practically is only to
guarantee right types to be used.

interface Point{
x: number;

readonly y: number;

let p1: Point = {x: 2, y: 3};

p1.x = 5;

*to change its props values. Readonly is to turn it unreassignable

Variables use const whereas properties use readonly to get unreassignable

Implementing Interfaces
interface IPrint{

print();//those classes implementing me must have a method

function printClass (a: IPrint) { console.log (a); return null;}

class ClassA implements IPrint{

print(){ console.log(`printing ClassA.print()`) }

let classA = new ClassA();

classA.print();

*to implement any interface in a class or in a function

Class Modifiers
Public

*For class property get assignable

class Pup{

constructor(public id: number){

}}

let pup = new Pup();

pup.id = 40

Private

*For class property get assignable only inside that class (or its constructor). Can only be externally
accessed by the class setter and getter methods

Static

*turns the prop usable without instantiating the class

class Pup{

static id: number;}

Pup.id = 40;

Extend

interface IBase{

id: number;}

interface IName extends IBase{

name: string;}

class Derived implements IName{

id: number;

name: string;//must have those 2 props, as described in interfaces

*extends an interface or a class. Interface inheritance. Class can extend and implement in same time
If more than more extend or implementation than use commas, to separate

Protected

*is almost like private

abstract class AbstractEmployee{

public id: number;

abstract getDetais(): string; //must be implemented in the inherited classes

public printDetail(){

console.log(`This’re the details ${this.getDetails()}`)

class NewEmployee extends AbstractEmployee {

getDetails(){

return `id: ${this.id}, name: ${this.name} `}

class NewManager extends NewEmployee{

public Employees: NewEmployees[],

getDetails(): string{

return super.getDetails() + `, Enployee count ${this.Employees.length}`};

Let employee = new NewEmployee();

employee.id = 1; employee.name = “Sara”; employee.printDetails();

Let manager = new NewManager();

manager.id = 1; manager.name = “Sara”; manager.Employees = new Array(); manager.printDetails();

Abstract class cannot be instantiated, are just to set functionalities that are shared among a group of
classes
Abtraction, inheritance and encapsulation are the base of OOP

Working with namespaces and modules


Any declaration (var, interface, function, class, etc.) can be exported to other files and imported from
other files

export class Abc{

a: string; b: string;}

ou

*to export any declaration so that it gets reusable in another ts files

export { d1 as sth1, d2 as sht2}

*in the end of the file to export all its declarations changing their names.

import { Abc as Alphabet } from “./file-name.ts”;

*to import any declaration so that it gets reusable in the current ts file. We can use Alias

import * as Langs from “./file-name.ts”;

*importing all expressions from a file. And access ‘em through Langs.declaration.

namespace Name{

classes and codes….


}

let name = new Name.itsclass();//instantiating a namespace to use its classes and more

*to create a namespace, to avoid similar class names compilation errors. Their like classes. A file may
have more than one namespace. Their declation must be exported to be accessed outside.

You might also like