Typescript and the tsc typescript compiler: Transpiling typescript to JavaScript

Understanding TypeScript Compilation

Today, we're diving deep into the world of TypeScript, specifically focusing on how TypeScript compiles into JavaScript. By the end of this lecture, you'll have a clearer understanding of the TypeScript compilation process
develop insight into how interpreted languages, and how compiled languages work
and why many developers prefer it over writing vanilla JavaScript.
The TypeScript Compilation Process
Parsing: The TypeScript compiler (tsc) starts by parsing the TypeScript code. This step involves reading the code and converting it into a data structure known as the Abstract Syntax Tree (AST).
Type Checking: Once the AST is generated, TypeScript performs type checking. This is where the magic happens! TypeScript checks the types you've defined against the operations you're performing to ensure type safety. If there are any type mismatches or violations, the compiler will throw an error.
Emitting: After type checking, the TypeScript compiler emits the corresponding JavaScript code. During this phase, all TypeScript-specific constructs, like interfaces and type annotations, are stripped away, resulting in pure JavaScript.
Why Use TypeScript and its Compiler?
Now, let's address a common question: Why not write JavaScript directly?
Type Safety: TypeScript's static type system catches type-related errors at compile-time. This means fewer runtime errors, which are often harder to debug and can be more costly in a production environment.
Better Tooling: With TypeScript, Integrated Development Environments (IDEs) can provide enhanced autocompletion, navigation, and refactoring capabilities. This is possible due to the type information available in the static code context.
Improved Readability: TypeScript's type annotations make the code more self-documenting. When you revisit your code or collaborate with others, these annotations provide clarity about the structure and expectations of the data.
Advanced Features: TypeScript offers features like interfaces, generics, and decorators, which aren't present in standard JavaScript. These features can lead to more maintainable and scalable code.
ESNext Features: TypeScript supports the latest ECMAScript features. You can write modern JavaScript, and the compiler can transpile it down to an older version for broader compatibility.
Student Questions
Student A: "If TypeScript is a superset of JavaScript, can I just rename my .js files to .ts and start using TypeScript?"
Answer: Technically, yes, because valid JavaScript is valid TypeScript. However, simply renaming won't give you the benefits of TypeScript's type system. To leverage TypeScript's advantages, you'd start by adding type annotations and utilizing its features.
Student B: "Doesn't adding types make development slower?"
Answer: Initially, it might seem that way because you're writing more annotations and dealing with type errors. However, in the long run, it saves time. Catching errors at compile-time, better tooling, and clearer code can significantly speed up debugging and development.
Student C: "Can I use TypeScript with popular JavaScript frameworks like React and Vue?"
Answer: Absolutely! Many popular JavaScript frameworks and libraries have embraced TypeScript or have community-provided type definitions. For instance, React components can be written using TypeScript, enhancing the development experience.
How does the typescript language server enforce type
The TypeScript Language Server, often referred to as the "TypeScript Language Service," plays a crucial role in providing developers with real-time feedback on their TypeScript code within Integrated Development Environments (IDEs) and text editors. It's responsible for features like autocompletion, error highlighting, and quick fixes. Let's dive into how it enforces types:

1. Parsing and Abstract Syntax Tree (AST):

The TypeScript Language Service starts by parsing the TypeScript code to produce an Abstract Syntax Tree (AST). The AST represents the hierarchical structure of the code, making it easier for the language service to analyze and understand the code's semantics.

2. Type Checking:

With the AST in hand, the language service performs type checking. It uses the type annotations provided in the code, along with type inference, to determine the expected types of variables, function parameters, return values, etc. If there's a mismatch between the expected type and the actual value or usage, the language service flags it as an error.

3. Symbol Resolution:

The language service resolves symbols (like variables, functions, classes) to their declarations and checks their usages against the provided type definitions. This is especially important in projects with multiple files or when using external libraries.

4. Type Inference:

Even if you don't explicitly provide type annotations everywhere in your TypeScript code, the language service can often infer types based on variable assignments, function return values, and other contextual clues. This helps in catching type-related issues even when types aren't explicitly annotated.

5. Real-time Feedback:

The TypeScript Language Service operates in real-time, providing immediate feedback as you type. This means that if you make a type-related mistake, you'll be alerted almost instantly in most modern IDEs or text editors that support TypeScript.

6. Integration with Declaration Files:

For external libraries that are originally written in JavaScript, TypeScript relies on declaration files (with a .d.ts extension) to understand the types. The language service uses these declaration files to enforce correct usage of external libraries.

7. Quick Fixes and Suggestions:

Beyond just flagging errors, the TypeScript Language Service often provides quick fixes and suggestions. For example, if you misspell a variable name or try to use a method that doesn't exist on a type, the language service can suggest the correct name or method.
The TypeScript Language Service is a powerful tool that operates behind the scenes in many development environments. It enforces type safety not just by relying on explicit type annotations but also through sophisticated type inference and symbol resolution mechanisms. This real-time feedback loop ensures that developers catch and fix type-related issues early in the development process, leading to more robust and maintainable codebases.

How does the typescript language service interact with the visual studio code debugger
Visual Studio Code (VS Code) is a popular code editor that has built-in support for TypeScript. The TypeScript Language Service and the VS Code debugger, while distinct components, work together to provide a seamless development experience. Let's explore how they interact:

1. TypeScript Language Service in VS Code:

When you work with TypeScript files in VS Code, the TypeScript Language Service is automatically activated. This service provides:
IntelliSense: Autocompletion, type information on hover, and inline documentation.
Real-time Error Checking: As you type, the service checks for type errors, syntax errors, and other issues, highlighting problematic code sections.
Refactoring: The service offers suggestions for refactoring, like extracting methods or renaming variables.
Navigation: Features like "Go to Definition" or "Find All References" are powered by the TypeScript Language Service.

2. VS Code Debugger:

VS Code has a built-in debugger that allows you to set breakpoints, inspect variables, and control the execution flow of your program. When debugging TypeScript, there are additional considerations:
Source Maps: Since TypeScript is transpiled to JavaScript, the code being executed by the Node.js runtime (or browser) is not the original TypeScript code. Source maps provide a mapping between the generated JavaScript code and the original TypeScript source, allowing the debugger to correlate the two. This means you can set breakpoints directly in your TypeScript code, even though the JavaScript version is what's actually running.

3. Interaction:

While the TypeScript Language Service and the VS Code debugger are separate components, their integration in VS Code makes them feel unified:
Error Navigation: If the TypeScript Language Service identifies an error, you can click on it to navigate directly to the problematic line. If this line causes a runtime error, the debugger will also highlight it, providing a smooth transition between compile-time and runtime error checking.
Consistent Views: When you hover over a variable while debugging, VS Code shows its current value. If you hover over the same variable outside of debugging mode, the TypeScript Language Service provides its type information. This consistent interface, regardless of whether you're debugging or just editing, enhances the development experience.
Integrated Terminal and Task Runners: VS Code's integrated terminal and task runners can be set up to run the TypeScript compiler. This means you can transpile your TypeScript code and then immediately debug it, all within the same environment.

The TypeScript Language Service and the VS Code debugger, while distinct, are integrated in a way that provides a cohesive and enhanced TypeScript development experience in VS Code. The editor abstracts away much of the complexity, allowing developers to focus on writing, understanding, and debugging their TypeScript code with ease.

While JavaScript is versatile and widely adopted, TypeScript offers a layer of safety, tooling, and features that can significantly enhance the development process, especially for larger applications. The decision to use TypeScript should be based on your project's needs, but understanding its benefits and the compilation process is crucial.
Thank you for joining today's lecture on TypeScript compilation. I encourage you to explore TypeScript further and consider its advantages in your future projects.
Technology background:
Node.js Full Stack application must run the Chromium JavaScript interpreter. Because many users will have old back versions of HTML Browsers and Chromium, we must support older browsers.
We write in TypeScript → tsc transpiles to JavaScript. Why not just write directly in JavaScript? Because we value developer productivity and we can write high quality code faster in TypeScript.
Learning Outcomes:
Understanding Typescript and the tsc typescript compiler
How the typescript compiler transpiles Typescript to JavaScript
The use cases for the advantages of of Object Oriented Typescript in building the controller for the mVC ecommerce website

Lecture: TypeScript and the TypeScript Compiler (tsc)
Today, we're diving into the world of TypeScript, a powerful superset of JavaScript that brings static typing to the table.

What is static typing?

There are 2 ways to execute program:

Dynamic Typing: For interpreted languages like JavaScript and Python: Language parser does one pass over the program code : => The output of this stage is called a Symbol Table. This symbol is provided as the input frame to the Language Server: which creates an AST Abstract Symbol tree - This AST is used by the Language Server to execute instructions in the operating system.

Statically typed language operation: In the first pass, the language parser still creates the AST: In a second pass, the language parser iterates over the AST :=> The output of this second pass is the LINKER file: The linker file contains the knowledge of the static types: static types are build up by parsing the AST. Static languages are COMPILED. The static symbol table is created BY the compiler and USED by the Language Server (Java for example). The Language Server can now direct the creation of OBJECTS. (Objects are in-memory data structures which bind the functions and data fields of classes with the ‘this’ keyword binding.

We'll also discuss the TypeScript compiler (tsc) and how it transpiles TypeScript to JavaScript.
Finally, we'll explore the advantages of using Object-Oriented TypeScript in building the controller for an MVC e-commerce website.
What is TypeScript?
TypeScript is a statically-typed superset of JavaScript developed by Microsoft. It adds optional types, classes, interfaces, and other features to JavaScript, making it easier to write robust and maintainable code, especially for large-scale applications.
What you can only have with a TYPED language:
Why TypeScript?
Static Typing: Unlike JavaScript, which is dynamically typed, TypeScript allows developers to specify / enforce types for variables, function parameters, and return values of objects. This helps catch type-related errors at compile-time rather than runtime.
Enhanced IDE Support: With TypeScript, IDEs can provide better intellisense: autocompletion, navigation, and refactoring capabilities.
Advanced Features: TypeScript offers features like interfaces, generics, and decorators, which aren't present in standard JavaScript.
The TypeScript Compiler (tsc)
The tsc or TypeScript compiler is a command-line tool that compiles TypeScript code into plain JavaScript. This transpilation process allows TypeScript to be run in any old JavaScript environment.
Basic Usage:
bashCopy code
tsc filename.ts

This will generate a corresponding filename.js with the transpiled JavaScript code.
Transpilation vs Compilation
While we often use the term "compile" when referring to TypeScript's transformation process, it's more accurate to call it "transpilation".
This is because TypeScript is being converted to another language at roughly the same level of abstraction (JavaScript), rather than being compiled down to a lower-level language like machine code.
Object-Oriented TypeScript for MVC E-commerce Controllers
When building an MVC (Model-View-Controller) e-commerce website, the controller plays a crucial role in handling user input and updating the view. Let's discuss why Object-Oriented TypeScript is advantageous for this:
Encapsulation: TypeScript classes allow us to bundle data (attributes) and methods (functions) that operate on the data into a single unit. This encapsulation ensures that the internal state of the controller is protected from external interference.
Inheritance: With TypeScript, controllers can inherit properties and methods from parent classes. This is useful for creating a base controller with common functionalities and then extending it for specific e-commerce sections like products, users, or orders.
Polymorphism: TypeScript enables us to define a single interface that can be implemented by multiple classes. This is beneficial when we need different controllers to be used interchangeably, all adhering to the same interface.
Strong Typing: By defining types for our data, we can ensure that our e-commerce controllers interact correctly with models and views. For instance, we can specify that a product ID should always be a number, preventing potential bugs.
Modularity: TypeScript's module system allows us to organize our controller code better, making it more maintainable and scalable.

TypeScript offers a plethora of features that make it a compelling choice for building large-scale applications, especially when combined with the MVC architecture.
The static typing, advanced OOP features, and powerful tooling provided by tsc make it an excellent choice for developing robust and maintainable e-commerce websites.
Continue to explore the applications of TypeScript further and look for ways to integrate these programming designs into your project code.

Lecture: TypeScript and the TypeScript Compiler (tsc)
Typescript and the tsc typescript compiler and how it transpiles typescript to JavaScript.
Use cases for the advantages of of Object Oriented Typescript in building the controller for the mVC ecommerce website

Example JavaScript node.js code that captures user form input and saves it to Typescript objects

Let's walk through a simple example where we capture user form input using an Express.js server and save the data to TypeScript objects.

1. Setting up the project:

First, initialize a new Node.js project and install the required packages:
bashCopy code
mkdir form-to-ts
cd form-to-ts
npm init -y
npm install express body-parser typescript @types/node @types/express

Next, initialize a TypeScript configuration:
bashCopy code
npx tsc --init

2. Create the TypeScript class:

Let's create a file named User.ts to define our TypeScript object:
typescriptCopy code
export class User {
public name: string,
public email: string
) {}

3. Create the Express server:

Create a file named server.ts:
typescriptCopy code
import express from 'express';
import bodyParser from 'body-parser';
import { User } from './User';

const app = express();

// Middleware to parse form submissions
app.use(bodyParser.urlencoded({ extended: true }));

// Serve the HTML form
app.get('/', (req, res) => {
<form action="/submit" method="post">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
<button type="submit">Submit</button>

// Handle form submission'/submit', (req, res) => {
const user = new User(,;
console.log(user); // Here, we're just logging the user object. In a real-world scenario, you'd likely save it to a database or perform other operations.
res.send('Form submitted successfully!');

const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);

4. Compile and run the server:

First, compile the TypeScript code:
bashCopy code
npx tsc

This will generate the corresponding JavaScript files. Now, run the server:
bashCopy code
node server.js

Visit http://localhost:3000 in your browser. Fill in the form and submit it. The server will capture the form input, create a TypeScript User object with the data, and log it to the console.
This example demonstrates how you can capture form data in a Node.js application and use it to instantiate TypeScript objects. In a real-world scenario, you'd likely take further actions with the object, such as saving it to a database or processing the data in some other way.

What it means to be a TypeScript OBJECT and contrast with JavaScript objects.
Highlight the benefits of Using TS objects in the node.js full stack ecommerce application

TypeScript Objects vs. JavaScript Objects
At a fundamental level, both TypeScript and JavaScript objects are collections of key-value pairs.
However, the distinction arises from TypeScript's static type system and its ability to define and enforce object shapes at compile-time.

TypeScript Objects:

Strong Typing: TypeScript objects can have explicit types assigned to their properties. This means you can define an object to have a specific shape, and the TypeScript compiler will enforce this shape. For instance, if a property is defined as a number, you can't assign a string to it without getting a compile-time error.
Class-based Objects: TypeScript supports ES6 class syntax and enhances it with features like access modifiers (private, public, protected), abstract classes, and interfaces. This makes it easier to implement object-oriented programming principles.
Interfaces: One of TypeScript's powerful features is the ability to define interfaces. An interface can be used to define a contract for the shape of an object. Classes can then implement these interfaces, ensuring they adhere to the specified shape.

JavaScript Objects:

Dynamically Typed: JavaScript objects are dynamically typed, meaning their properties can hold values of any type, and these can be changed or added on the fly. There's no built-in mechanism to enforce a specific shape or type for an object.
Prototype-based: JavaScript uses prototype-based inheritance. While ES6 introduced class syntax to JavaScript, it's primarily syntactical sugar over its prototypal nature.
Benefits of Using TypeScript Objects in a Node.js Full Stack E-commerce Application:
Robustness: With TypeScript's static type checking, many errors, especially those related to data structures and types, are caught at compile-time rather than runtime. This can prevent numerous bugs that might arise during user interactions on an e-commerce platform.
Improved Readability: Explicit type annotations make the code more self-documenting. Developers can easily understand the structure of data, making collaboration and maintenance more straightforward.
Enhanced Tooling: TypeScript's strong typing provides better IDE support. Features like auto-completion, type checking, and refactoring become more powerful and accurate, leading to increased developer productivity.
Scalability: As e-commerce platforms grow, so does their codebase. TypeScript's features, like modules and namespaces, help in organizing and managing large codebases, ensuring the application remains scalable and maintainable.
Safety with Third-party Libraries: When using third-party libraries or APIs, TypeScript's declaration files (.d.ts) can provide type definitions, ensuring that the library's functions and methods are used correctly.
In conclusion, while JavaScript objects offer flexibility due to their dynamic nature, TypeScript objects bring structure, robustness, and clarity, especially beneficial for large-scale applications like e-commerce platforms. By leveraging TypeScript in a Node.js full stack e-commerce application, developers can ensure a more reliable, maintainable, and developer-friendly environment.

Typescript with React and Mongodb:

Let's clarify the history and purpose of TypeScript and its relationship with React and MongoDB.


Origin: TypeScript was developed by Microsoft and first released in October 2012. Its primary goal was to bring static typing to JavaScript, making it easier to develop large-scale applications. TypeScript is a superset of JavaScript, meaning any valid JavaScript code is also valid TypeScript.
Purpose: TypeScript introduces optional static typing, interfaces, generics, and other features that are not present in standard JavaScript. These features make it easier to catch bugs at compile-time, refactor code, and develop large applications with better tooling and developer experience.


React is a JavaScript library for building user interfaces, developed by Facebook. It was released in 2013, after TypeScript's initial release.
TypeScript with React: While React was initially developed with JavaScript in mind, the adoption of TypeScript in the React community has grown over time. TypeScript can be used with React to define component props, state, and context with static types. This provides better error checking, autocompletion, and a more robust development experience. However, React doesn't require TypeScript; it's just a popular and beneficial combination.


MongoDB is a NoSQL database that stores data in a JSON-like format. It's unrelated to TypeScript in terms of its primary function.
TypeScript with MongoDB: When developing Node.js applications that interact with MongoDB, TypeScript can be used to define the shape of data, ensuring that the application interacts with the database in a type-safe manner. Libraries like Mongoose, which is used to model application data for MongoDB, can be paired with TypeScript type definitions to ensure data consistency.


TypeScript was not developed specifically for React or MongoDB. Instead, it was designed to enhance JavaScript with static typing and other features to improve the development of large-scale applications. Over time, as both React and MongoDB became popular in the JavaScript ecosystem, developers found value in using TypeScript alongside them to ensure type safety, better tooling, and a more robust development experience.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.