Share
Explore

Typescript and the tsc typescript compiler: Transpiling typescript to JavaScript


megaphone

Understanding TypeScript Compilation

Introduction
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.

Conclusion
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)
Introduction
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?

info

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:
Polymorphism
Encapsulation
Composition
Inheritance/Subclassing
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.
Reference:
Loading…
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 {
constructor(
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) => {
res.send(`
<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>
</form>
`);
});

// Handle form submission
app.post('/submit', (req, res) => {
const user = new User(req.body.name, req.body.email);
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:
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.