Share
Explore

TypeScript Lab

References:

Step Up Steps

Install TypeScript into your Node.js Environment
npm init
npm install -g typescript
** Mac Users use HOMEBREW: You must take special procedures due to the strict MAC OS Security
Check with for the steps. TypeScript is a NODE Package.
Install the VSC Extensions to help you with TypeScript.
That’s it. Now you are a TypeScript Programmer.
image.png

Introduction to TypeScript: Lab and Lecture

Lab Overview:
In this lab, we will explore the fundamentals of TypeScript, a statically typed superset of JavaScript.
TypeScript = JavaScript with OBJECTS: We need this for our project:
Controller: Needs Business Objects to implement Business Rules
Express: Needs objects to convey data between Model and Front End
MONGO: Needs typescript! Plus calls backs and other TypeScript Function formulations we practiced in

We will cover the installation of TypeScript, the configuration of TypeScript projects in Visual Studio Code, and demonstrate how to run TypeScript code using the TypeScript compiler.
Additionally, we will provide examples that showcase the power and advantages of using TypeScript in real-world scenarios.
Lecture Outline:
Introduction to TypeScript
Overview of TypeScript and its benefits
Key features and advantages compared to JavaScript
Installing TypeScript
Installing Node.js and npm (Node Package Manager)
Using npm to install TypeScript globally
Setting up a TypeScript Project in Visual Studio Code
Creating a new project directory
Initializing a TypeScript project using "npm init"
Configuring TypeScript in a project (tsconfig.json)
Writing and Compiling TypeScript Code
Writing TypeScript code using Visual Studio Code
Understanding type annotations and inference
Transpiling TypeScript to JavaScript using the TypeScript compiler (tsc)
Running TypeScript Code
Configuring a build task in Visual Studio Code to automatically compile TypeScript
Running the compiled JavaScript code in Node.js or a web browser
Examples of TypeScript in Action
Example 1: Creating a class with type annotations
Example 2: Implementing interfaces and leveraging type checking
Example 3: Working with modules and import/export statements
Lab Instructions:
Install TypeScript:
Install Node.js and npm by following the official documentation for your operating system.
Open a terminal or command prompt and execute the following command:
Copy code
npm install -g typescript
Set up a TypeScript Project:
Create a new project directory using the command:

mkdir my-ts-project
Change into the project directory:
bashCopy code
cd my-ts-project
Initialize the project using npm:
npm init -y
Create a new file called "app.ts" in the project directory and write some TypeScript code.
Configure TypeScript in Visual Studio Code:
Open Visual Studio Code and open the project directory.
Create a new file called "tsconfig.json" in the root of the project directory.
Add the following content to "tsconfig.json":
jsonCopy code
{ "compilerOptions": { "target": "es5", "module": "commonjs", "outDir": "dist" }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules" ] }
Transpile and Run TypeScript Code:
Open the "app.ts" file in Visual Studio Code and write some TypeScript code.
Open the integrated terminal in Visual Studio Code (Ctrl + `).
Run the following command to compile the TypeScript code:

tsc
Verify that the JavaScript code has been generated in the "dist" folder.
Execute the compiled JavaScript code using Node.js:
bashCopy code
node dist/app.js
Observe the output.
Explore Examples:
Review the provided examples in the lab materials and try running them in your project.
Experiment with modifying the code to see how TypeScript helps with type safety and tooling support.
References:
TypeScript Official Documentation:
Visual Studio Code Documentation:
Node.js Official Website:
Note: It is important to keep your TypeScript and Node.js versions up to date to leverage the latest features and bug fixes.

TypeScript Lab and Lecture for Students
Introduction
This lab and lecture are designed to introduce students to TypeScript, a statically typed superset of JavaScript that compiles to plain JavaScript. TypeScript offers classes, modules, and interfaces that help in building robust components [1].
Part I: Lecture
What is TypeScript?: TypeScript is a programming language developed by Microsoft. It's a statically typed superset of JavaScript, which means it adds new features and enhancements to JavaScript while still allowing you to run your code as regular JavaScript [1].
Advantages of TypeScript: TypeScript helps in the development of large-scale JavaScript applications, ensuring better maintainability and scalability [3].
Installation: To get started with TypeScript in Visual Studio Code, you need to install the TypeScript compiler. This can be done through the Integrated Terminal in Visual Studio Code [1].
Part II: Lab
Running a "Hello World" Program in TypeScript: Start by creating a simple "Hello World" program in TypeScript. Using Visual Studio Code, you can compile the TypeScript code to JavaScript and execute it [1].
For example:
typescript
let message: string = 'Hello World';
console.log(message);
Using IntelliSense: IntelliSense in Visual Studio Code offers smart completions based on variable types, function definitions, and imported modules. It can be used to modify the behavior of the TypeScript compiler [1].
For instance:
typescript
Copy code
let student: {name: string, age: number};
student = {name: "John", age: 20};
With IntelliSense, you'll see automatic suggestions as you type the structure of the student object.
Debugging TypeScript: Visual Studio Code has built-in support for TypeScript debugging, allowing you to set breakpoints, step through your code, and inspect variables directly within the editor [1].
For instance, if there's an error in the following code:
typescript
Copy code
let students: {name: string, age: number}[];
students.push({name: "John", age: 20});
You can debug and find that students array was not initialized before using the push method.
Conclusion
TypeScript's additional features make it a valuable tool for developing large-scale JavaScript applications. The combination of TypeScript with Visual Studio Code provides a powerful environment for development, with features like IntelliSense and built-in debugging support [1].
References
[1] TypeScript in Visual Studio Code
[3] Best online resources to learn TypeScript
References:

Here are 5 progressively more instructive student labs teaching the core concepts and features of TypeScript:

Lab 1: Basic Types
In this lab, students will learn about the basic types in TypeScript and how to use them.
Create a new TypeScript file called basicTypes.ts.
Define a variable myNumber of type number and assign it a value of 42.
Define a variable myString of type string and assign it a value of "Hello, world!".
Define a variable myBoolean of type boolean and assign it a value of true.
Define a variable myArray of type number[] and assign it an array of numbers.
Define a variable myTuple of type [string, number] and assign it a tuple of a string and a number.
Define a variable myEnum of type enum and assign it an enum of colors.
Define a variable myAny of type any and assign it any value.
Compile the TypeScript file using the TypeScript compiler (tsc basicTypes.ts) and run the resulting JavaScript file (node basicTypes.js).
Observe the output and verify that the types are correct.
Lab 2: Functions
In this lab, students will learn about functions in TypeScript and how to use them.
Create a new TypeScript file called functions.ts.
Define a function add that takes two parameters of type number and returns their sum.
Define a function greet that takes a parameter of type string and returns a greeting message.
Define a function calculate that takes two parameters of type number and a function of type (a: number, b: number) => number and returns the result of applying the function to the parameters.
Compile the TypeScript file using the TypeScript compiler (tsc functions.ts) and run the resulting JavaScript file (node functions.js).
Observe the output and verify that the functions work correctly.
Lab 3: Classes
In this lab, students will learn about classes in TypeScript and how to use them.
Create a new TypeScript file called classes.ts.
Define a class Person with properties name and age.
Define a constructor that takes parameters name and age and assigns them to the properties.
Define a method greet that returns a greeting message.
Define a subclass Student that extends Person with a property major.
Define a constructor that takes parameters name, age, and major and assigns them to the properties.
Define a method study that returns a message about studying.
Compile the TypeScript file using the TypeScript compiler (tsc classes.ts) and run the resulting JavaScript file (node classes.js).
Observe the output and verify that the classes work correctly.
Lab 4: Interfaces
In this lab, students will learn about interfaces in TypeScript and how to use them.
Create a new TypeScript file called interfaces.ts.
Define an interface Person with properties name and age.
Define a function greet that takes a parameter of type Person and returns a greeting message.
Define an interface Student that extends Person with a property major.
Define a function study that takes a parameter of type Student and returns a message about studying.
Compile the TypeScript file using the TypeScript compiler (tsc interfaces.ts) and run the resulting JavaScript file (node interfaces.js).
Observe the output and verify that the interfaces work correctly.
Lab 5: Modules
In this lab, students will learn about modules in TypeScript and how to use them.
Create a new TypeScript file called modules.ts.
Define a class Person with properties name and age.
Define a constructor that takes parameters name and age and assigns them to the properties.
Define a method greet that returns a greeting message.
Export the Person class.
Create a new TypeScript file called main.ts.
Import the Person class from modules.ts.
Create a new instance of the Person class and call the greet method.
Compile the TypeScript files using the TypeScript compiler (tsc modules.ts main.ts) and run the resulting JavaScript file (node main.js).
Observe the output and verify that the modules work correctly.


Here is the complete TypeScript code that fetches and displays a joke from the Klingon Jokes API every time it is called:
typescript
interface Joke {
id: number;
joke: string;
}

async function fetchJoke(): Promise<Joke> {
const response = await fetch('https://klingon-jokes-api.herokuapp.com/api/jokes');
const data = await response.json();
return data;
}

async function displayJoke(): Promise<void> {
try {
const joke = await fetchJoke();
console.log(joke.joke);
} catch (error) {
console.log('Error:', error);
}
}

displayJoke();

In this code, we define an interface Joke that describes the structure of a joke object returned by the Klingon Jokes API.
The fetchJoke function uses the fetch function to send a GET request to the API endpoint. It awaits the response and then parses the JSON data using the json method. The function returns the joke data as a Promise<Joke>.
The displayJoke function is an async function that calls the fetchJoke function to retrieve a joke. It awaits the result and then logs the joke to the console. If an error occurs during the fetch or parsing process, it catches the error and logs an error message.
Finally, we call the displayJoke function to fetch and display a joke from the Klingon Jokes API.
Note that this code uses the fetch function, which is a modern way to make HTTP requests in JavaScript and TypeScript. It returns a Promise that resolves to the response, allowing us to use await to handle the asynchronous operation.
Not AccurateView SourcesCopy To ClipboardEdit Query
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.