0% found this document useful (0 votes)
37 views52 pages

Lecture #15. Typescript

The document provides an overview of TypeScript, a programming language developed by Microsoft that extends JavaScript with static typing and is suitable for large applications. It covers the advantages of TypeScript, including early error detection, better structure for large projects, and compatibility with JavaScript, as well as installation instructions for Node.js and the TypeScript compiler. Additionally, it explains various data types, functions, classes, and access modifiers in TypeScript.

Uploaded by

yarychroma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views52 pages

Lecture #15. Typescript

The document provides an overview of TypeScript, a programming language developed by Microsoft that extends JavaScript with static typing and is suitable for large applications. It covers the advantages of TypeScript, including early error detection, better structure for large projects, and compatibility with JavaScript, as well as installation instructions for Node.js and the TypeScript compiler. Additionally, it explains various data types, functions, classes, and access modifiers in TypeScript.

Uploaded by

yarychroma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Web design

Lecture #15. Typescript


The organization issues

Use this link to confirm your attendance in the lecture

Лабораторна робота №1

Лабораторна робота №2

Лабораторна робота №3

Контрольна робота №4 - наступного разу!

2
Introduction to TypeScript

TypeScript is a programming language developed and maintained by Microsoft.


It is a strict syntactical superset of JavaScript and adds optional static typing to the language.
TypeScript is designed for the development of large applications and transcompiles to
JavaScript.
As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript
programs.
TypeScript may be used to develop JavaScript applications for both client-side and server-side
execution (as with Node.js).
Typescript & Javascript
TypeScript builds on top of JavaScript. First, we write the TypeScript code. Then, compile the
TypeScript code into plain JavaScript code using a TypeScript compiler.
Once you have the plain JavaScript code, you can deploy it to any environments that JavaScript runs.
TypeScript Setup
Node.js – Node.js is the environment on which we will run the TypeScript
compiler. Note that we don’t need to know node.js.
TypeScript compiler – a Node.js module that compiles TypeScript into
JavaScript. If you use JavaScript for node.js, you can install the ts-node module. It
is a TypeScript execution and REPL for node.js
Visual Studio Code or VS code – is a code editor that supports TypeScript. VS
Code is highly recommended. However, you can use your favorite editor.
Live Server – allows you to launch a development local Server with the hot reload
feature.
Typescript Advantages
1. Static Typing
Allows you to specify types for variables, functions, and objects.
Errors are caught at compile time, not at runtime.

function add(a: number, b: number): number {


return a + b;
}
2. Autocompletion and Hints in IDEs
Thanks to the type system, code editors (like VS Code and others) can:
Suggest methods and properties.
Warn about errors before running the program.
Show documentation directly in the editor.

3. Better Structure and Support for Large Projects


TypeScript allows the use of interfaces, classes, modules, and generics.
This makes the code scalable, easier to maintain, and self-documenting.
Typescript Advantages
4. Early Error Detection
Reduces the number of runtime errors, which are often hard to diagnose in
JavaScript.
For example, calling undefined.someMethod() will no longer go unnoticed during
development.

5. Compatibility with JavaScript


All valid JavaScript is also valid TypeScript.
You can gradually introduce TS into an existing JS project.

6, Improved Development Workflow


Better refactoring, autocompletion, type checking, and CI/CD integration.
interface User {
name: string;
age: number;
}
function greet(user: User) {
console.log(`Hello, ${user.name}`);
Node.js & Typescript installation
To install node.js, follow these steps:
● Go to the node.js download page.
● Download the node.js version that suits your platform i.e., Windows, macOS, or Linux.
● Execute the downloaded node.js package or execution file. The installation is quite
straightforward.
To install the TypeScript compiler, you launch the Terminal on macOS or Linux and Command Prompt
on Windows and type the following command:
npm install -g typescript
After the installation, you can type the following command to check the current version of the
TypeScript compiler:
tsc --v (Version 5.7.2)
Typescript to Javascript
enum Color { var Color;
RED = "red", (function (Color) {
BLUE = "blue", Color["RED"] = "red";
GREEN = "green", Color["BLUE"] = "blue";
} Color["GREEN"] = "green";
})(Color || (Color = {}));
enum Engine {
V6 = "v6", var Engine;
V8 = "v8", (function (Engine) {
ELECTRIC = "electric", Engine["V6"] = "v6";
} Engine["V8"] = "v8";
Engine["ELECTRIC"] = "electric";
class Car { })(Engine || (Engine = {}));
color: Color;
engine: Engine; var Car = /** @class */ (function () {
brand: string; function Car(color, engine, brand,
model: string; model) {
this.color = color;
constructor(color: Color, engine: Engine, brand: this.engine = engine;
string, this.brand = brand;
model: string) { this.model = model;
this.color = color; }
this.engine = engine; return Car;
this.brand = brand; }());
this.model = model;
} var myCar = new Car(Color.BLUE,
} Engine.ELECTRIC, "Tesla", "Model 3");
const myCar = new Car(Color.BLUE, Engine.ELECTRIC,
"Tesla", "Model 3");

tsc app.ts (generates app.js)


Typescript: Hello World

let message: string = 'Hello, World!';


// create a new heading 1 element
let heading = document.createElement('h1');
heading.textContent = message;
// add the heading the document
document.body.appendChild(heading);

tsc app.ts (generates app.js)


index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TypeScript: Hello, World!</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
Types in TypeScript

Boolean
The most basic datatype is the simple true/false value, which JavaScript and
TypeScript call a boolean value.
let isDone: boolean = false;
Types in TypeScript

Number
As in JavaScript, all numbers in TypeScript are either floating point values or
BigIntegers. These floating point numbers get the type number, while
BigIntegers get the type bigint. In addition to hexadecimal and decimal literals,
TypeScript also supports binary and octal literals introduced in ECMAScript 2015.
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
let big: bigint = 100n;
Types in TypeScript

String
Just like JavaScript, TypeScript also uses double quotes (") or single quotes (') to
surround string data.
let color: string = "blue";
color = 'red';
We can also use template strings, which can span multiple lines and have
embedded expressions. These strings are surrounded by the backtick/backquote
(`) character, and embedded expressions are of the form ${ expr }.
Types in TypeScript

Array
TypeScript, like JavaScript, allows you to work with arrays of values. Array types
can be written in one of two ways. In the first, you use the type of the elements
followed by [] to denote an array of that element type:
let list: number[] = [1, 2, 3];
The second way uses a generic array type, Array<elemType>:
let list: Array<number> = [1, 2, 3];
Types in TypeScript
Tuple
Tuple types allow you to express an array with a fixed number of elements whose types are
known, but need not be the same.
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
Types in TypeScript

When accessing an element with a known index, the correct type is retrieved:
console.log(x[0].substring(1)); // OK
console.log(x[1].substring(1)); // error:
Property 'substring' does not exist on type 'number'.

x[3] = "world";
Tuple type '[string, number]' of length '2' has no element at index '3'.
Types in TypeScript
Enum
A helpful addition to the standard set of datatypes from JavaScript is the enum. As in languages like
C#, an enum is a way of giving more friendly names to sets of numeric values.
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
By default, enums begin numbering their members starting at 0.
Types in TypeScript
Unknown
Values may come from dynamic content – e.g. from the user – or we may want to intentionally
accept all values in our API. In these cases, we want to provide a type that tells the compiler and
future readers that this variable could be anything, so we give it the unknown type.
let notSure: unknown = 4;
notSure = "maybe a string instead";
// OK, definitely a boolean
notSure = false;
declare const maybe: unknown;
// 'maybe' could be a string, object,
boolean, undefined, or other types
const aNumber: number = maybe;
Type 'unknown' is not assignable to type
'number'.
Types in TypeScript
Any
In some situations, not all type information is available or its declaration would take an inappropriate
amount of effort. These may occur for values from code that has been written without TypeScript or
a 3rd party library. In these cases, we might want to opt-out of type checking. To do so, we label
these values with the any type:
declare function getValue(key: string): any;
// OK, return value of 'getValue' is not checked
const str: string = getValue("myString");
Unlike unknown, variables of type any allow you to access arbitrary properties, even ones that
don’t exist.
TypeScript 3.0 introduces a new top type unknown. unknown is the type-safe counterpart of any.
Anything is assignable to unknown, but unknown isn’t assignable to anything but itself
and any without a type assertion or a control flow based narrowing. Likewise, no operations are
permitted on an unknown without first asserting or narrowing to a more specific type.
Types in TypeScript

Void
void is a little like the opposite of any: the absence of having any type at all. You may
commonly see this as the return type of functions that do not return a value:
function warnUser(): void {
console.log("This is my warning message");
}
Declaring variables of type void is not useful because you can only assign null (only if --
strictNullChecks is not specified, see next section) or undefined to them:
let unusable: void = undefined;
// OK if `--strictNullChecks` is not given
unusable = null;
Types in TypeScript

Null and Undefined


In TypeScript, both undefined and null actually have their types named undefined and null
respectively. Much like void, they’re not extremely useful on their own:

// Not much else we can assign to these variables!


let u: undefined = undefined;
let n: null = null;
Types in TypeScript
Never
The never type represents the type of values that never occur.
For instance, never is the return type for a function expression or an arrow function expression
that always throws an exception or one that never returns.
Variables also acquire the type never when narrowed by any type guards that can never be true.

// Function returning never must not have a reachable end point


function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
Types in TypeScript
Object
object is a type that represents the non-primitive type, i.e. anything that is not number, string,
boolean, bigint, symbol, null, or undefined.

With object type, APIs like Object.create can be better represented. For example:

declare function create(o: object | null): void;

// OK
create({ prop: 0 });
create(null);

create("string"); //error
TypeScript functions

function name(parameter: type, parameter:type,...): returnType {


// do something
}
Unlike JavaScript, TypeScript allows you to use type annotations in
parameters and return value of a function.

function add(a: number, b: number): number {


return a + b;
}

When you call the add() function, the TypeScript compiler will check each
argument passed to the function to ensure that they are numbers.
TypeScript functions

TypeScript compiler will match the number of parameters with their types and the return type.

The following example shows how to assign a function to the add variable:

add = function (x: number, y: number) {


return x + y;
};
Also, you can declare a variable and assign a function to a variable like this:

let add: (a: number, b: number) => number =


function (x: number, y: number) {
return x + y;
};
TypeScript Optional Parameters

In TypeScript, the compiler checks every function call and issues an error in the
following cases:
● The number of arguments is different from the number of parameters
specified in the function.
● Or the types of arguments are not compatible with the types of function
parameters.
TypeScript Optional Parameters

function multiply(a: number, b: number, c?: number): number {

if (typeof c !== 'undefined') {


return a * b * c;
}
return a * b;
}
The optional parameters must appear after the required parameters in the
parameter list.
TypeScript default parameters

function name(parameter1=defaultValue1,...) {
// do something
}
In this syntax, if you don’t pass arguments or pass the undefined into the
function when calling it, the function will take the default initialized values for
the omitted parameters. For example:
function applyDiscount(price, discount = 0.05) {
return price * (1 - discount);
}
console.log(applyDiscount(100)); // 95
TypeScript function overloadings

In TypeScript, function overloadings allow to establish the relationship between


the parameter types and result types of a function.
function addNumbers(a: number, b: number): number {
return a + b;
}
function addStrings(a: string, b: string): string {
return a + b;
}
Function overloading with
optional parameters
When we overload a function, the number of required parameters must be
the same. If an overload has more parameters than the other, you have to make
the additional parameters optional. For example:
function sum(a: number, b: number): number;
function sum(a: number, b: number, c: number): number;
function sum(a: number, b: number, c?: number): number {
if (c) return a + b + c;
return a + b;
}
Classes
TypeScript class adds type annotations to the properties and methods of the class. The
following shows the Person class in TypeScript:

class Person {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
let person = new Person('John', 'Smith');
TypeScript Access Modifiers

Access modifiers change the visibility of the properties and methods of a class.
TypeScript provides three access modifiers:
private
protected
public
Note that TypeScript controls the access logically during compilation time,
not at runtime.
TypeScript Access Modifiers

The private modifier


The private modifier limits the visibility to the same-class only.
The public modifier
The public modifier allows class properties and methods to be accessible from all locations. If we
don’t specify any access modifier for properties and methods, they will take the public
modifier by default.
The protected modifier
The protected modifier allows properties and methods of a class to be accessible within same
class and within subclasses.
When a class (child class) inherits from another class (parent class), it is a subclass of the parent
class.
TypeScript Access Modifiers

class Person {

constructor(private firstName: string, protected lastName: string) {


this.firstName = firstName;
this.lastName = lastName;
}

getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
TypeScript readonly

TypeScript provides the readonly modifier that allows you to mark the properties of a class
immutable. The assignment to a readonly property can only occur in one of two places:

● In the property declaration.


● In the constructor of the same class.

class Person {
readonly birthDate: Date;

constructor(birthDate: Date) {
this.birthDate = birthDate;
}
}
Readonly vs. const

readonly
Use for Class properties Variables

const
Initialization In the declaration or in the constructor of the same class
In the declaration
TypeScript inheritance

TypeScript supports inheritance like ES6:

class Employee extends Person {


//..
}
TypeScript Static Methods and
Properties

Unlike an instance property, a static property is shared among all instances of a


class.

class Employee {
static headcount: number = 0;

public static getHeadcount() {


return Employee.headcount;
}
}
...
Employee.headcount++;
Employee.getHeadcount();
TypeScript abstract classes

An abstract class is typically used to define common behaviors for derived classes
to extend.
Unlike a regular class, an abstract class cannot be instantiated directly.
abstract class Employee {
constructor(private firstName: string, private lastName: string) {
}
abstract getSalary(): number
}
TypeScript abstract classes

class FullTimeEmployee extends Employee {


constructor(firstName: string, lastName: string, private salary: number) {
super(firstName, lastName);
}
getSalary(): number {
return this.salary;
}
}
TypeScript interfaces

The following uses an interface called Person that has two string properties:
interface Person {
firstName: string;
last Name: string;
}
By convention, the interface names are in the camel case. They use a single
capitalized letter to separate words in there names. For example, Person,
UserProfile, and FullName.
TypeScript interfaces

function getFullName(person: Person) {


return `${person.firstName} ${person.lastName}`;
}
let john = {
firstName: 'John',
lastName: 'Smith'
};
console.log(getFullName(john));
Optional properties

An interface may have optional properties. To declare an optional property, you


use the question mark (?) at the end of the property name in the declaration, like
this:

interface Person {
firstName: string;
middleName?: string;
lastName: string;
}
Function types
To describe a function type, we assign the interface to the function signature that contains the
parameter list with types and returned types. For example:

interface StringFormat {
(str: string, isUpper: boolean): string
}

let format: StringFormat;

format = function (str: string, isUpper: boolean) {


return isUpper ? str.toLocaleUpperCase() : str.toLocaleLowerCase();
};

console.log(format('hi', true)); // HI
Class Types

For example, the following Json interface can be implemented by any unrelated
classes:
interface Json {
toJSON(): string
}
class Person implements Json {
constructor(private firstName: string,
private lastName: string) {
}
toJson(): string {
return JSON.stringify(this);
}
}
Interfaces extending
interface Mailable {
send(email: string): boolean
queue(email: string): boolean
}
interface FutureMailable extends Mailable {
later(email: string, after: number): boolean
}
An interface can extend multiple interfaces, creating a combination of all the interfaces.
TypeScript Generics
TypeScript generics allow to write the reusable and generalized form of functions, classes, and
interfaces. In this tutorial, you’re focusing on developing generic functions.

function getRandomElement<T>(items: T[]): T {


let randomIndex = Math.floor(Math.random() * items.length);
return items[randomIndex];
}

let numbers = [1, 5, 7, 4, 2, 9];


let colors = ['red', 'green', 'blue'];

console.log(getRandomAnyElement(numbers));
console.log(getRandomAnyElement(colors));
Typescript Singleton
class MySingleton {

static instance: MySingleton; const myInstance1: MySingleton =


static a: number = 0; MySingleton.getInstance();
const myInstance2: MySingleton =
private constructor() {
MySingleton.getInstance();
console.log("constructor called!");
} const myInstance3: MySingleton =
public static getA() {return MySingleton.getInstance();
MySingleton.a;} const myInstance4: MySingleton =
public static getInstance(): MySingleton
MySingleton.getInstance();
{
MySingleton.a++; MySingleton.getA(); // 4
if (!MySingleton.instance) { A = new MySingleton()
MySingleton.instance = new
MySingleton();
//The VehicleHandler is "abstract" because noone
Typescript Factory is going to instantiate it
//We want to extend it and implement the
interface Vehicle { abstract method
move(): void abstract class VehicleHandler {
}
//This is the method real handlers need to
//The classes we care about, the "move" method implement
is where our "business logic" would live public abstract createVehicle(): Vehicle
class Car implements Vehicle {
//This is the method we care about, the rest of
public move(): void { the business logic resides here
console.log("Moving the car!") public moveVehicle(): void {
} const myVehicle = this.createVehicle()
} myVehicle.move()
}
class Bicycle implements Vehicle { }

public move(): void { //Here is where we implement the custom object


type InternalState = {
event: String
}
Typescript Observer
abstract class Observer {
abstract update(state:InternalState): void
}

abstract class Observable {

protected observers: Observer[] = [] //the


list of observers
protected state:InternalState = { event: "" }
//the internal state observers are watching

public addObserver(o:Observer):void {
this.observers.push(o)
}

protected notify() {
VueJS/Typescript Example Project

Pomodoro technique application available on Github


A Pomodoro Timer built with Vue 3, TypeScript, and Pinia.
- Pomodoro timer with customizable durations
- Short and long breaks
- Settings panel
- Auto-start options

52

You might also like