02_ES6_TypeScript
02_ES6_TypeScript
—
Full Stack Development – COSC2769/COSC2808
1
RMIT Classification: Trusted
Agenda
• Brief history
• New features
• Asynchronous programming
▪ TypeScript
22
RMIT Classification: Trusted
Brief history
44
RMIT Classification: Trusted
New features
55
RMIT Classification: Trusted
66
RMIT Classification: Trusted
77
RMIT Classification: Trusted
88
RMIT Classification: Trusted
99
RMIT Classification: Trusted
10
10
RMIT Classification: Trusted
• The … (spread) operator - more examples: function arguments (left - top), copying an array
11
11
RMIT Classification: Trusted
12
12
RMIT Classification: Trusted
• Default parameters
13
13
RMIT Classification: Trusted
14
14
RMIT Classification: Trusted
Asynchronous programming
15
15
RMIT Classification: Trusted
Event handler
▪ Event handler
• Provide a function which is called a callback function
• The function will be called when the event happens
16
16
RMIT Classification: Trusted
Callback function
17
17
RMIT Classification: Trusted
Promise
18
18
RMIT Classification: Trusted
Promise (2)
▪ let myPromise = new Promise(function(resolve, reject) {
let r = Math.random();
if (r >= 0.5) {
resolve(r);
} else {
reject(r);
}
});
▪ To use the above promise, we provide two functions for the two outcomes and pass to the
promise then() method
▪ myPromise.then(
(v) => console.log(`Fulfilled for value ${v}`),
(v) => console.log(`Rejected for value ${v}`),
);
▪ Rejected event can also be handled by catch() method
▪ myPromise.catch(
(v) => console.log(`Rejected for value ${v}`)
);
19
19
RMIT Classification: Trusted
Promise (3)
▪ Promise objects also support finally() method. This method accepts a function that is called
when the promise is settled (either fulfilled or rejected)
▪ When a value is returned in a then() callback, that value is wrapped in a promise. So, you
can call then() on the next promise, and so on
▪ myPromise.then((v) => function1(v)).then((v) => function2(v)).then((v) =>
function3(v));
▪ Promise.all() static method takes an iterable of promises as input and returns a single
promise. This returned promise fulfills when all the input's promises fulfill, with an array of
the fulfillment values. It rejects when any of the input's promises rejects, with this first
rejection reason
▪ The static method Promise.any() has an opposite behavior
20
20
RMIT Classification: Trusted
▪ An async function returns a promise. The returned value is the promise value when it is
fulfilled
▪ Inside an async function, the await keyword is permitted
▪ The await keyword makes the function pause and wait for a resolved promise before it
continues
▪ Let’s say you want to authenticate a user. The following steps are required
• Step 1: connect to a DB
• Step 2: retrieve data from a table
• Step 3: compare the retrieved data with the user provided data
▪ As Step 1 and Step 2 interact with an external system, they return promises. So, your code
is something like
• connect(dbConfig).then((ok) => retrieveData()).then((data) => compareData(data));
21
21
RMIT Classification: Trusted
▪ Instead of doing as before, we can use await keyword inside an async function
▪ The steps now become
• async function validate() {
const connection = await connect(dbConfig);
const data = await retrieveData();
compareData(data);
}
▪ await can only be used inside an async function
▪ Using await can make asynchronous programming behaves like synchronous programming
▪ Example: the fetch() API
• The fetch() API retrieve a resource
• The return value of fetch() is a promise that resolves to a Response object
▪ The public API endpoint https://catfact.ninja/fact returns a random fact about cat. Let's use
fetch() to get some interesting facts about cats
22
22
RMIT Classification: Trusted
23
23
RMIT Classification: Trusted
24
24
RMIT Classification: Trusted
25
25
RMIT Classification: Trusted
Workers (*)
▪ In a single-threaded program, all statements must be executed one by one
▪ Workers allow some tasks to run in a different thread
▪ Once JavaScript starts a task in a new thread, it runs the next task immediately
▪ Multiple threads can access to the same shared data => may lead to unexpected results
▪ As a result, the main thread and worker threads should not share data. They should
communicate by sending messages to each other
▪ This example from MDN Web Docs illustrate the use of web workers and how to
communicate between the main thread and worker threads
▪ The main components in the above example:
• generate.js: this code runs in a worker thread. It listens for the event "generate" from the main thread, then
starts the function generatePrimes(). Once the execution of the function generatePrimes() finishes, it sends a
message to the main thread by calling postMessage() method
• main.js: this code starts a new worker thread with the code given in the generate.js file. It calls the
postMessage() method to send an event 'generate' to the worker. It also registers a listener for the event
'message', so it can receive the result sent back by the worker
26
26
RMIT Classification: Trusted
27
27
RMIT Classification: Trusted
Intro to TypeScript
28
28
RMIT Classification: Trusted
Hello, TypeScript
• Compilation result
29
29
RMIT Classification: Trusted
ts-node
• You can also install ts-node, a TypeScript execution and REPL for NodeJS
• REPL (Read, Evaluate, Print, and Loop): let you input TypeScript code and get the result
immediately
• Installation: npm install -g ts-node
30
30
RMIT Classification: Trusted
Primitive types
• If you don't specify the type, TypeScript infers the type automatically
31
31
RMIT Classification: Trusted
Array
• Array of numbers
• let nums: number[] = [1, 2, 3];
▪ Array of strings
• let names: string[] = ['Alice', 'Bob', 'Carol'];
▪ Array of objects
• let students: object[] = [
{id: 123, name: 'Alice', major: 'IT', GPA: 3.0},
{id: 456, major: 'SE', GPA: 3.2},
];
▪ Array of any
• let arr: any[] = [1, 'two', true, 'four'];
▪ Array of union types
• let arr: (string | number)[] = [1, 'two', 3, 'four'];
32
32
RMIT Classification: Trusted
33
33
RMIT Classification: Trusted
34
34
RMIT Classification: Trusted
Class
35
35
RMIT Classification: Trusted
More features
• https://www.typescriptlang.org/cheatsheets/
36
36
RMIT Classification: Trusted
—
Thank you
Tri Dang
[email protected]
37