TypeScript 是 JavaScript 的型別超集,可編譯為純 JavaScript。它將靜態類型添加到您的程式碼中,從而更容易在開發過程中捕獲錯誤。
設定 TypeScript
首先,讓我們設定 TypeScript:
npm install -g typescript
tsc --init
要編譯 TypeScript 檔案 (.ts),請執行:
tsc filename.ts
讓我們從一些基本類型和有趣的例子開始。
let greeting: string = "Hello, TypeScript!"; console.log(greeting); // Hello, TypeScript!
let age: number = 42; console.log(`I'm ${age} years old!`); // I'm 42 years old!
let isHappy: boolean = true; console.log(`Am I happy? ${isHappy}`); // Am I happy? true
想像一個只能理解特定類型的機器人:
let robotName: string = "RoboCop"; let robotAge: number = 100; let isRobotFriendly: boolean = true; console.log(`Meet ${robotName}, who is ${robotAge} years old. Friendly? ${isRobotFriendly}`); // Meet RoboCop, who is 100 years old. Friendly? true
TypeScript 陣列只能保存一種類型的資料:
let fruits: string[] = ["Apple", "Banana", "Cherry"]; console.log(fruits); // ["Apple", "Banana", "Cherry"]
一隻貓整理它的玩具收藏(只有球):
let catToys: string[] = ["Ball1", "Ball2", "Ball3"]; console.log(catToys); // ["Ball1", "Ball2", "Ball3"]
元組允許您表達具有固定數量且類型已知的元素的數組:
let myTuple: [string, number]; myTuple = ["Hello", 42]; // OK console.log(myTuple); // ["Hello", 42]
想像一個有代號和 ID 號碼的超級特工:
let agent: [string, number] = ["Bond", 007]; console.log(agent); // ["Bond", 007]
TypeScript 允許您指定函數的參數類型和傳回值。
function add(a: number, b: number): number { return a + b; } console.log(add(5, 3)); // 8
拿著魔勺的廚師:
function mixIngredients(ingredient1: string, ingredient2: string): string { return `${ingredient1} mixed with ${ingredient2}`; } console.log(mixIngredients("Flour", "Sugar")); // Flour mixed with Sugar
介面定義物件的結構。
interface Person { name: string; age: number; } let user: Person = { name: "Alice", age: 30 }; console.log(user); // { name: "Alice", age: 30 }
一隻會說話的狗,有一張特別的身分證:
interface Dog { name: string; breed: string; } let talkingDog: Dog = { name: "Scooby-Doo", breed: "Great Dane" }; console.log(talkingDog); // { name: "Scooby-Doo", breed: "Great Dane" }
TypeScript 類別是建立具有初始值和方法的物件的藍圖。
class Animal { name: string; constructor(name: string) { this.name = name; } move(distance: number = 0) { console.log(`${this.name} moved ${distance} meters.`); } } let dog = new Animal("Dog"); dog.move(10); // Dog moved 10 meters.
超級英雄課程:
class Superhero { name: string; constructor(name: string) { this.name = name; } saveTheCat() { console.log(`${this.name} saved the cat!`); } } let hero = new Superhero("Batman"); hero.saveTheCat(); // Batman saved the cat!
枚舉允許我們定義一組命名常數。
enum Direction { Up, Down, Left, Right } let move: Direction = Direction.Up; console.log(move); // 0
交通燈系統:
enum TrafficLight { Red, Yellow, Green } let light: TrafficLight = TrafficLight.Green; console.log(light); // 2
_您剛剛快速瀏覽了 TypeScript,從基本類型到泛型和枚舉等更高級的功能。透過這些範例,您應該有一個良好的起點,可以在專案中進一步探索和使用 TypeScript。
如果您有任何具體問題或需要有關 TypeScript 任何部分的更多有趣範例,請隨時詢問! _
以上是TypeScript 簡介的詳細內容。更多資訊請關注PHP中文網其他相關文章!