Basics of TypeScript

Basics of TypeScript

This article explains the basics of TypeScript.

YouTube Video

Executing "Hello World!"

First, we'll run the classic "Hello World!" example in TypeScript using Visual Studio Code.

npm install -g typescript

Install typescript using the npm command.

Create a tsconfig.json file.

1{
2  "compilerOptions": {
3    "target": "ES6",
4    "module": "CommonJS",
5    "outDir": "out",
6    "sourceMap": true
7  }
8}

Create a .vscode/launch.json file to enable running the main.ts file in Visual Studio Code.

 1{
 2    "version": "0.2.0",
 3    "configurations": [
 4        {
 5            "type": "node",
 6            "request": "launch",
 7            "name": "Launch Program",
 8            "skipFiles": [
 9                "<node_internals>/**"
10            ],
11            "program": "${workspaceFolder}/main.ts",
12            "preLaunchTask": "tsc: build - tsconfig.json",
13            "outFiles": [
14                "${workspaceFolder}/out/main.js"
15            ]
16        }
17    ]
18}

Create a main.ts file that displays "Hello World!". You can run it in Visual Studio Code by pressing the F5 key.

1console.log("Hello World!");

By configuring this way, you can execute TypeScript files within VSCode.

Overview of TypeScript

TypeScript (TS) is a superset of JavaScript developed by Microsoft. TypeScript supports static typing, allowing for more robust and maintainable code.

Static Typing

  • TypeScript adds types to JavaScript and performs type checking at compile time. This allows for preventing type-related bugs in advance.
1let message: string = "Hello, TypeScript";
2console.log(message);

Compilation

  • Since TypeScript cannot be directly executed in a browser, it needs to be transpiled (compiled) to JavaScript. Use tsc (TypeScript Compiler) to convert TS files to JS files.

Optional Type Annotations

  • TypeScript also performs type inference but allows you to explicitly specify types when necessary. This improves code readability and reliability.
1function greet(name: string): string {
2    return `Hello, ${name}`;
3}
4console.log(greet('John'));

Interfaces

  • TypeScript provides interface to define the shape of objects. This allows for strict management of object structure.
1interface Person {
2    name: string;
3    age: number;
4}
5const user: Person = { name: "John", age: 30 };
6console.log(user.name);

Classes

  • TypeScript provides extensions to JavaScript's class syntax and supports inheritance, access modifiers (public, private, protected), and abstract classes.
 1class Animal {
 2    protected name: string;
 3    constructor(name: string) {
 4        this.name = name;
 5    }
 6    speak(): void {
 7        console.log(`${this.name} makes a sound.`);
 8    }
 9}
10
11class Dog extends Animal {
12    speak(): void {
13        console.log(`${this.name} barks.`);
14    }
15}
16const animal = new Animal('Generic Animal');
17animal.speak();
18
19const dog = new Dog('Buddy');
20dog.speak();

Generics

  • In TypeScript, you can write reusable and type-safe code using generics.
1function identity<T>(arg: T): T {
2    return arg;
3}
4console.log(identity<string>("Hello Generics"));

Ecosystem

  • TypeScript is fully compatible with the JavaScript ecosystem and can use existing JavaScript code as is. Furthermore, it is integrated with popular libraries such as React and Node.js.

Powerful Developer Tools

  • TypeScript offers advanced features such as autocomplete, refactoring support, and error checking in editors like VSCode.

TypeScript is particularly useful for enhancing reliability and improving developer productivity in large projects.

Variables in TypeScript

This explains the basic concepts and usage of variables in TypeScript.

Variable Declaration

In TypeScript, variables are declared using three keywords: let, const, and var. Each keyword has different characteristics.

Example of let:

let has block scope (valid only within curly braces {}). Values can be reassigned later.

1let count: number = 10;
2console.log(count);  // Outputs: 10
3
4count = 20;
5console.log(count);  // Outputs: 20

Example of const:

const cannot be reassigned, so the value assigned once cannot be changed. However, the contents of objects and arrays can be modified.

1const pi: number = 3.14;
2console.log(pi);  // Outputs: 3.14
3
4// pi = 3.14159; // Error: Reassignment is not allowed
5
6const fruits: string[] = ["apple", "banana"];
7fruits.push("orange");
8console.log(fruits);  // Outputs: ["apple", "banana", "orange"]

Example of var:

var has function scope and can be reassigned. However, ignoring block scope, it may cause unexpected behavior compared to let or const.

 1var message: string = "Hello, world!";
 2console.log(message);  // Outputs: Hello, world!
 3
 4message = "Hello, TypeScript!";
 5console.log(message);  // Outputs: Hello, TypeScript!
 6
 7// (`var` ignores block scope)
 8if (true) {
 9    var localMessage = "Hello again!";
10}
11console.log(localMessage); // "Hello again!"

Type Annotations

In TypeScript, you can explicitly annotate types for variables. Type inference is also supported, but type annotations are useful in complex scenarios.

1let isDone: boolean = false;
2console.log(isDone);  // Outputs: false
3
4let userName: string = "Alice";
5console.log(userName);  // Outputs: Alice

Uninitialized Variables

If a variable is declared without initialization, undefined is assigned by default. A variable declared with let must be explicitly assigned undefined or include undefined in its type if not initialized.

1let uninitialized: number | undefined;
2console.log(uninitialized);  // Outputs: undefined
3
4uninitialized = 5;
5console.log(uninitialized);  // Outputs: 5

Variable Scope

let and const have block scope, so they are only valid within the same block.

1if (true) {
2    let blockScoped: string = "Block Scoped";
3    console.log(blockScoped);  // Outputs: Block Scoped
4}
5// console.log(blockScoped);  // Error: blockScoped is out of scope

Variable Hoisting

Since TypeScript is a superset of JavaScript, it inherits JavaScript's hoisting feature. Hoisting refers to the behavior where variable and function declarations are treated as if they are lifted to the top of their scope. However, only the declaration is hoisted, while the initialization remains in place. Variables declared with var are hoisted, but using let or const before declaration results in an error.

1console.log(a); // undefined
2var a = 10;
3console.log(a); // 10
  • In this case, variables declared with var are hoisted, and their values are output.
1console.log(b); // ReferenceError
2let b = 20;
  • Variables declared with let are not hoisted, resulting in an error.

Summary

The following is a summary of let, const, and var.

  • let is reassignable and has block scope.
  • const is not reassignable and has block scope.
  • var is reassignable and has function scope.
  • All of them allow explicit type annotation for specifying variable types.

Escape Characters in TypeScript

Escape characters are used when specific characters cannot be entered directly or to represent characters that have special meaning within a string. In TypeScript, escape characters are used to represent control characters or special characters.

For example, use \n to output a message that includes a newline.

1const message: string = "Hello,\nWorld!";
2console.log(message);
3// Output:
4// Hello,
5// World!

Escaping Special Characters

Escape characters are also useful when including special characters in a string. For instance, you may want to use double quotes or single quotes directly within a string.

1const singleQuoteExample: string = 'It\'s a beautiful day!';
2console.log(singleQuoteExample);
3// Output: It's a beautiful day!
4
5const doubleQuoteExample: string = "He said, \"Welcome!\"";
6console.log(doubleQuoteExample);
7// Output: He said, "Welcome!"

Escaping the Backslash Itself

To include a backslash in a string, you need to write it as a double backslash.

1const path: string = "C:\\Program Files\\MyApp";
2console.log(path);
3// Output: C:\Program Files\MyApp

Unicode and Hexadecimal Escapes

In TypeScript, Unicode code points can be represented using escape sequences.

Unicode Escape Sequence

You can represent Unicode characters by specifying a four-digit hexadecimal number after \u.

1const smileyFace: string = "\u263A";
2console.log(smileyFace);
3// Output: ☺ (Copyright Mark)

Hexadecimal Escape

You can represent specific characters using a two-digit hexadecimal number after \x.

1const letterA: string = "\x41";
2console.log(letterA);
3// Output: A

Template Literals and Escapes

Template literals are defined by enclosing them in backticks and provide an easy way to create embedded expressions or multi-line strings. Regular escape characters can be used directly in template literals.

1const multiLine: string = `This is
2a multi-line
3string.`;
4console.log(multiLine);
5// Output:
6// This is
7// a multi-line
8// string.

Special Cases

In TypeScript, using invalid escape sequences within a string may result in a syntax error. Therefore, it is important to check whether the escape characters are valid.

1// Invalid escape sequence
2const invalidString: string = "\xZZ"; // Error

Practical Usage Examples

Here is an example of constructing a complex string using escape characters.

1const jsonExample: string = "{\n\t\"name\": \"John Doe\",\n\t\"age\": 30\n}";
2console.log(jsonExample);
3// Output:
4// {
5//     "name": "John Doe",
6//     "age": 30
7// }

In this example, \n is used for a newline and \t is used to add indentation. This makes the JSON structure easier to read.

Summary

Escape characters are very important when working with strings in TypeScript. When you want to include special characters or control characters in a string, you can create expressive strings by using appropriate escape sequences. Understanding and using escape characters correctly can improve code readability and maintainability.

Versions of TypeScript

Let's take an overview of the TypeScript version here.

  1. TypeScript 1.0 (2014)

    The first stable version of TypeScript. Basic features such as typing, classes, and modules were introduced.

  2. TypeScript 2.0 (2016)

    Non-nullable Types, Control Flow Analysis, Read-only Properties, and Never type were introduced, enhancing type inference.

  3. TypeScript 3.0 (2018)

    A more flexible type system was introduced, with features like Project References, Tuple Types extensions, and improvements to Rest Parameters.

  4. TypeScript 4.0 (2020)

    Features such as Variadic Tuple Types, editor improvements, enhanced type inference, and Labelled Tuple Elements were added to improve the development experience.

  5. TypeScript 4.1 (2020)

    Template Literal Types were introduced, making string type manipulation more powerful.

  6. TypeScript 4.3 (2021)

    The addition of the Override keyword, improvements to access modifiers within constructors, and enhanced type support for WeakMap and WeakSet.

  7. TypeScript 4.5 (2021)

    The Awaited type, ModuleSuffixes, and improved compatibility with ECMAScript modules were added.

  8. TypeScript 5.0 (2023)

    Standardization of Decorators, improvement in project build speed, enhancement of type system, and support for the latest ECMAScript features have been made.

TypeScript is constantly evolving, with multiple versions released each year introducing new features and improvements.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video