TypeScript 提供了多種內建型別(primitive types),以下是常見的幾種:
boolean
:布林值(true
或 false
)number
:數字,支持整數和浮點數string
:字符串null
:表示空值undefined
:表示未定義void
:表示沒有任何返回值的函數any
:表示任何類型,用於逐步遷移 JavaScript 代碼never
:表示不會發生的類型,例如會拋出錯誤或無限循環的函數範例:
let isDone: boolean = false;
let age: number = 30;
let firstName: string = "John";
let u: undefined = undefined;
let n: null = null;
TypeScript 通常不進行隱式轉換,但在特定情況下,例如算術運算,會有類似 JavaScript 的隱式轉換:
let value: any = "123";
let result: number = value + 10; // 隱式轉換成字符串拼接,result = "12310"
顯式轉換是指開發者明確地將一個類型轉換為另一個類型,有兩種方式:
let value: any = "123";
let valueAsNumber: number = value as number;
let value: any = "123";
let valueAsNumber: number = <number>value;
TypeScript 支持創建自訂型別,包括介面(interface)和類別(class):
interface Person {
firstName: string;
lastName: string;
age?: number; // 可選屬性
}
let person: Person = {
firstName: "John",
lastName: "Doe"
};
class Employee {
fullName: string;
constructor(public firstName: string, public lastName: string) {
this.fullName = `${firstName} ${lastName}`;
}
greet(): string {
return `Hello, ${this.fullName}`;
}
}
let employee = new Employee("Jane", "Doe");
console.log(employee.greet());
元組(tuple)是一種特殊的數組,允許你指定元素的類型和數量:
let tuple: [string, number];
tuple = ["hello", 42]; // 正確
// tuple = [42, "hello"]; // 錯誤
集合型別包括 Set
和 Map
:
let set: Set<number> = new Set([1, 2, 3, 4]);
set.add(5);
console.log(set); // Set { 1, 2, 3, 4, 5 }
let map: Map<string, number> = new Map();
map.set("one", 1);
map.set("two", 2);
console.log(map); // Map { 'one' => 1, 'two' => 2 }
陣列可以包含相同類型的一組元素:
let numbers: number[] = [1, 2, 3, 4, 5];
let strings: Array<string> = ["a", "b", "c"]; // 泛型語法
字典型別(也稱為映射類型)允許我們定義鍵值對的集合:
interface Dictionary {
[key: string]: number;
}
let dict: Dictionary = {};
dict["foo"] = 42;
dict["bar"] = 100;
這些是 TypeScript 中常見的型別系統和相關概念。理解和使用這些型別可以提高代碼的可讀性和可維護性。