TypeScript - Types: A Beginner's Guide

Hello there, future coding superstar! Today, we're diving into the fascinating world of TypeScript types. Don't worry if you've never written a line of code before – I'll be your friendly guide on this exciting journey. By the end of this tutorial, you'll be amazed at how much you've learned. So, let's get started!

TypeScript - Types

What are Types in TypeScript?

Before we jump into the deep end, let's talk about what types are and why they're important. Think of types as labels we put on our data. Just like how we organize our closet with different sections for shirts, pants, and shoes, types help us organize our code and prevent us from putting a metaphorical sock in the shirt drawer!

TypeScript is a superset of JavaScript that adds optional static typing. This means we can tell TypeScript exactly what kind of data we're working with, which helps catch errors before our code even runs. It's like having a helpful friend looking over your shoulder, pointing out potential mistakes before you make them.

The Any Type: The Wild Card of TypeScript

Let's start with the most flexible type in TypeScript: any. It's like the joker in a deck of cards – it can be anything!

let myVariable: any = 42;
myVariable = "Hello, World!";
myVariable = true;

In this example, myVariable can be a number, then a string, then a boolean. It's very flexible, but with great power comes great responsibility. Using any too often defeats the purpose of using TypeScript, so use it sparingly!

Built-in Types: The Building Blocks of TypeScript

TypeScript comes with several built-in types that cover most of our needs. Let's explore them one by one:

1. Number

let age: number = 30;
let price: number = 9.99;

Numbers in TypeScript can be integers or floating-point values. No need to worry about different number types like in some other languages!

2. String

let name: string = "Alice";
let greeting: string = `Hello, ${name}!`;

Strings can be defined with single quotes, double quotes, or backticks. Backticks allow us to embed expressions using ${}.

3. Boolean

let isStudent: boolean = true;
let hasPassedExam: boolean = false;

Booleans are simple – they're either true or false. Think of them as yes/no questions for your code.

4. Array

let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: Array<string> = ["apple", "banana", "orange"];

Arrays can hold multiple values of the same type. We can define them using square brackets or the Array<T> syntax.

5. Tuple

let person: [string, number] = ["Alice", 30];

Tuples are arrays with a fixed number of elements, where each element can have a different type. They're like a small, organized box with specific compartments for each item.

6. Enum

enum Color {
Red,
Green,
Blue
}
let favoriteColor: Color = Color.Blue;

Enums allow us to define a set of named constants. They're great for representing a fixed set of options.

7. Void

function logMessage(message: string): void {
console.log(message);
}

Void is used to indicate that a function doesn't return anything. It's like sending a letter without expecting a reply.

8. Null and Undefined

let notDefined: undefined = undefined;
let empty: null = null;

These types represent the absence of a value. They're like empty boxes – one that's intentionally empty (null) and one that hasn't been filled yet (undefined).

Here's a table summarizing the built-in types we've covered:

Type Description Example
number Numeric values (integer or floating-point) let age: number = 30;
string Textual data let name: string = "Alice";
boolean True or false values let isStudent: boolean = true;
array Collection of values of the same type let numbers: number[] = [1, 2, 3];
tuple Fixed-length array with elements of specific types let person: [string, number] = ["Alice", 30];
enum Set of named constants enum Color { Red, Green, Blue }
void Absence of a return value in functions function logMessage(message: string): void { ... }
null Intentional absence of any object value let empty: null = null;
undefined Variable that hasn't been assigned a value let notDefined: undefined = undefined;

User-defined Types: Crafting Your Own Tools

Now that we've covered the built-in types, let's talk about how you can create your own custom types. This is where TypeScript really shines!

1. Interfaces

Interfaces allow us to define the structure of an object. Think of them as blueprints for objects.

interface Person {
name: string;
age: number;
greet(): void;
}

let alice: Person = {
name: "Alice",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};

In this example, we've defined a Person interface and created an object that adheres to this structure. It's like creating a form that people need to fill out – everyone needs to provide the same information.

2. Classes

Classes are a way to create reusable components. They're like cookie cutters – you define the shape once, and then you can make as many cookies (objects) as you want!

class Student {
name: string;
grade: number;

constructor(name: string, grade: number) {
this.name = name;
this.grade = grade;
}

study() {
console.log(`${this.name} is studying hard!`);
}
}

let bob = new Student("Bob", 10);
bob.study(); // Outputs: "Bob is studying hard!"

Here, we've created a Student class with properties (name and grade) and a method (study). We can create as many students as we want using this class.

3. Type Aliases

Type aliases allow us to create new names for types. They're useful for creating complex types or giving more meaningful names to existing types.

type Point = {
x: number;
y: number;
};

let center: Point = { x: 0, y: 0 };

In this example, we've created a Point type that represents a point in 2D space. It's a simple way to group related properties together.

4. Union Types

Union types allow a value to be one of several types. It's like saying, "This can be either this or that."

type Result = number | string;

function getResult(value: boolean): Result {
return value ? "Success" : 404;
}

Here, Result can be either a number or a string. This is useful when a value could be of different types depending on certain conditions.

5. Intersection Types

Intersection types combine multiple types into one. It's like saying, "This must be this AND that."

interface Colorful {
color: string;
}

interface Circle {
radius: number;
}

type ColorfulCircle = Colorful & Circle;

let myCircle: ColorfulCircle = {
color: "red",
radius: 5
};

In this example, ColorfulCircle is both Colorful and a Circle. It must have both a color and a radius.

And there you have it! We've covered the basics of TypeScript types, from the flexible any type to built-in types and user-defined types. Remember, types in TypeScript are like your coding superpowers – they help you write cleaner, more reliable code and catch errors before they become problems.

As you continue your TypeScript journey, keep experimenting with these types. Try combining them in different ways, and don't be afraid to make mistakes – that's how we learn! Before you know it, you'll be typing away like a pro, creating robust and error-free code.

Happy coding, and may your types always be strong!

以下是繁體中文的翻譯:

TypeScript - 類型:初學者指南

你好,未來的編程超級巨星!今天,我們將深入探索 TypeScript 类型的迷人世界。別擔心如果你之前從未寫過一行代碼——我將成為你這次令人興奮旅程中的友好指南。在這個教程結束時,你會驚訝於自己學到了多少。那麼,讓我們開始吧!

TypeScript中的類型是什麼?

在我們跳進深水區之前,讓我們先來討論一下類型是什麼,以及它們為什麼重要。可以把類型看作是我們貼在我們數據上的標籤。就像我們用不同的區域來組織衣櫥中的襯衫、褲子和鞋子一樣,類型幫助我們組織代碼,防止我們將一個比喻性的襪子放在襯衫抽屜裡!

TypeScript 是 JavaScript 的超集,它添加了可選的靜態類型。這意味著我們可以告訴 TypeScript 我們正在使用的是什麼類型的數據,這有助於在我們的代碼甚至還未運行之前就捕獲錯誤。這就像有一個友好的朋友在旁邊查看你的肩膀,指出你可能的錯誤。

The Any Type: TypeScript的萬能牌

讓我們從 TypeScript 中最靈活的類型開始:any。它就像一副牌中的小丑——它可以是一切!

let myVariable: any = 42;
myVariable = "Hello, World!";
myVariable = true;

在這個例子中,myVariable 可以是數字,然後是字符串,然後是布尔值。它非常靈活,但隨著力量的增強,責任也越大。過度使用 any 會導致 TypeScript 的目的失敗,所以謹慎使用!

內置類型:TypeScript的基礎

TypeScript 提供了多種內置類型,它們涵蓋了我們大部分的需求。讓我們一一探索它們:

1. 數字(Number)

let age: number = 30;
let price: number = 9.99;

TypeScript 中的數字可以是整數或浮點數值。不需要擔心像其他語言中那樣的不同數字類型!

2. 字符串(String)

let name: string = "Alice";
let greeting: string = `Hello, ${name}!`;

字符串可以用單引號、雙引號或反引號定義。反引號允許我們使用 ${} 嵌入表達式。

3. 布爾值(Boolean)

let isStudent: boolean = true;
let hasPassedExam: boolean = false;

布爾值很簡單——它們只能是 true 或 false。把它們看作是代碼中的是/否問題。

4. 陣列(Array)

let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: Array<string> = ["apple", "banana", "orange"];

陣列可以保存同一類型的多個值。我們可以使用方括號或 Array<T> 語法來定義它們。

5. 元祖(Tuple)

let person: [string, number] = ["Alice", 30];

元祖是具有固定數量元素的數組,其中每個元素可以有不同的類型。它們就像一個小而有序的盒子,每個物品都有特定的隔間。

6. 枚舉(Enum)

enum Color {
Red,
Green,
Blue
}
let favoriteColor: Color = Color.Blue;

枚舉允許我們定義一組命名常量。它們很適合表示一組固定的選項。

7. Void

function logMessage(message: string): void {
console.log(message);
}

Void 用於表示函數不返回任何東西。這就像寄出一封信而不期待回覆。

8. Null 和 Undefined

let notDefined: undefined = undefined;
let empty: null = null;

這些類型表示值的缺失。它們就像空盒子——一個是有意為空的(null),另一個是尚未填滿的(undefined)。

以下是內置類型的總結表:

類型 描述 示例
number 數值(整數或浮點數) let age: number = 30;
string 文本數據 let name: string = "Alice";
boolean 布爾值(true 或 false) let isStudent: boolean = true;
array 同類型值的集合 let numbers: number[] = [1, 2, 3];
tuple 固定長度數組,元素類型可以不同 let person: [string, number] = ["Alice", 30];
enum 命名常量的集合 enum Color { Red, Green, Blue }
void 函數中沒有返回值的標誌 function logMessage(message: string): void { ... }
null 有意為空的對象值 let empty: null = null;
undefined 未賦值的變量 let notDefined: undefined = undefined;

用户定义类型:打造自己的工具

現在我們已經介紹了內置類型,讓我們來討論如何創建自己的自定义類型。這是 TypeScript 真正閃光的地方!

1. 接口(Interfaces)

接口允許我們定義對象的結構。把它們看作是對象的藍圖。

interface Person {
name: string;
age: number;
greet(): void;
}

let alice: Person = {
name: "Alice",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};

在這個例子中,我們定義了一個 Person 接口並創建了一個符合這個結構的對象。這就像創建一個表單,人們需要填寫——每個人都需要提供相同的資訊。

2. 类(Classes)

類是一種創建可重用組件的方式。它們就像曲奇模具——你定義一次形狀,然後可以制作出許多曲奇(對象)!

class Student {
name: string;
grade: number;

constructor(name: string, grade: number) {
this.name = name;
this.grade = grade;
}

study() {
console.log(`${this.name} is studying hard!`);
}
}

let bob = new Student("Bob", 10);
bob.study(); // 輸出:"Bob is studying hard!"

在這裡,我們創建了一個 Student 類,它有屬性(namegrade)和一個方法(study)。我們可以使用這個類來創建許多學生。

3. 类型别名(Type Aliases)

类型别名允許我們為類型創建新名稱。它們在創建复杂数據類型或為现有類型提供更有意義的名稱時很有用。

type Point = {
x: number;
y: number;
};

let center: Point = { x: 0, y: 0 };

在這個例子中,我們創建了一個 Point 类型,它代表二维空間中的一個點。這是一種將相關屬性組織在一起的簡單方式。

4. 联合类型(Union Types)

联合类型允許一個值是幾種类型中的一种。就像說,“這可以是這個或那個。”

type Result = number | string;

function getResult(value: boolean): Result {
return value ? "Success" : 404;
}

在這裡,Result 可以是數字或字符串。當一個值可能根據某些條件有不同的类型時,這很有用。

5. 交集类型(Intersection Types)

交集类型將多個类型組合成一個。就像說,“這必須是這個和那個。”

interface Colorful {
color: string;
}

interface Circle {
radius: number;
}

type ColorfulCircle = Colorful & Circle;

let myCircle: ColorfulCircle = {
color: "red",
radius: 5
};

在這個例子中,ColorfulCircleColorfulCircle。它必須有 colorradius

就这样!我們已經介紹了 TypeScript 类型的基礎,從靈活的 any 类型到內置类型和用户定义类型。記住,TypeScript 中的类型就像你的編程超能力——它們幫助你寫出更乾淨、更可靠的代碼,並在它們成為問題之前捕獲錯誤。

當你繼續你的 TypeScript 旅程時,請繼續嘗試這些類型。嘗試以不同的方式組合它們,並不要害怕犯錯誤——這是學習的過程!在你意識到之前,你將

Credits: Image by storyset