TS Introduction

This section dives deeper into how TypeScript works and why it is beneficial. You will learn the basic structure of a TypeScript program, how types are enforced, and see a simple "Hello World" example.

Key Topics

What is TypeScript?

TypeScript is an open-source language that builds on JavaScript by adding optional static typing. It helps catch errors early through type-checking, and it makes code more reliable and maintainable. TypeScript supports all JavaScript libraries and frameworks.

Why Use TypeScript?

  • Early Error Detection: Catch bugs before runtime with type checks.
  • Better Tooling: Enjoy powerful autocompletion and refactoring tools.
  • Large-Scale Projects: Scales well for enterprise-level applications.
  • Seamless JS Integration: Any valid JavaScript code is also valid TypeScript.

Basic Example

Below is a simple TypeScript example demonstrating the advantage of static typing.

// hello.ts
function greetUser(name: string) {
    return `Hello, ${name}!`;
}

console.log(greetUser("Alice"));
// console.log(greetUser(42)); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.

Output

Hello, Alice!

Explanation: When transpiled, the TypeScript compiler would flag the second greetUser(42) call because 42 is not a string. This helps catch errors before running the code.

Transpilation Example

TypeScript code must be transpiled into JavaScript. By default, the command tsc hello.ts generates a hello.js file that you can run in any JavaScript environment.

tsc hello.ts
node hello.js

Explanation: After transpilation, the hello.js file contains plain JavaScript, compatible with browsers and Node.js.

Key Takeaways

  • Static Typing: TypeScript adds type safety to JavaScript, reducing runtime errors.
  • Familiar Syntax: Almost all JavaScript syntax is valid TypeScript.
  • Transpilation: TypeScript code is compiled into standard JavaScript for broad compatibility.