2.5 KiB
Step 2.1: Introduction to TypeScript (Exercise)
If you don't already have the app running, start it by running npm start from the root of the frontend-bootcamp folder.
Exercises will be completed under this step's exercise/src folder unless otherwise noted. You'll also want to open the Step2-01 exercise page to see the results as you work.
Modules
-
Open the file
exercise/src/fibonacci.tsin VS Code -
Inside this file, write a function called
fib(n)that takes in a number and returns then-th Fibonacci number (be sure the specify the type ofn).
HINT:
function fib(n: number) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); }
-
Export
fib(n)as a named export -
Export a const variable
FibConstas a default export -
Inside
index.tsin the same folder, import bothfibandFibConst, and use the built-inconsole.log()function to log the result offib(FibConst).
Types and Interfaces
Inside exercise/src/index.ts:
-
Add a type alias for string union type describing the states of Red-Green-Yellow traffic light:
type TrafficLight = ??? -
Describe a type of car with an interface:
interface Car { ... }complete withwheels,color,make,model -
Create a valid car instance and log it using
console.log():const myCar: Car = { ??? };
Generics
Inside exercise/src/stack.ts, create a generic class for a Stack<T> complete with a typed pop() and push() methods.
Hint: the JavaScript array already has
push()andpop()implemented for you. That can be your backing store.
In exercise/src/index.ts, create a Stack<number> and use console.log() to demonstrate its functionality.
Spread and Destructuring
- Note the following code in index.ts:
const obj1 = {
first: 'who',
second: 'what',
third: 'dunno',
left: 'why'
};
const obj2 = {
center: 'because',
pitcher: 'tomorrow',
catcher: 'today'
};
-
Now create a one-liner using the spread syntax
{...x, ...y}to create a new variablemegaObjthat combines these two objects. -
Use the destructuring syntax to retrieve the values for
{first, second, catcher}frommegaObj.
Async / Await
Note the following code in index.ts:
function makePromise() {
return Promise.resolve(5);
}
-
Call
makePromise()with theawaitsyntax and log the results. -
Create a new function that uses the
asynckeyword. Inside the function, make anawaitcall tomakePromise()and return the results.