1. TypeScript 簡介
1.1 什麼是 TypeScript?
-
TypeScript(TS) 是由 Microsoft 開發的 JavaScript 超集合 (Superset)。
-
它在 JavaScript 基礎上加入了 靜態型別檢查、類別 (Class)、介面 (Interface)、泛型 (Generics) 等功能。
-
最終 一定要編譯成 JavaScript 才能在瀏覽器或 Node.js 執行。
💡 可以理解為:
TypeScript 是更嚴謹、更結構化的 JavaScript,幫助你在開發時提前找出錯誤。
2. TypeScript 轉 JavaScript
因為瀏覽器和 Node.js 原生只懂 JavaScript,所以 TS 必須 編譯(Transpile) 成 JS 才能執行。
2.1 安裝 TypeScript 編譯器
前提先安裝node.js
-
全域安裝 TypeScript
npm install -g typescript
-
檢查版本
tsc -v
3.目前先寫個簡單的print功能
創一個檔案 01-helloword.ts
console.log("Hello, World!");
先確定node.js有安裝之後先安裝npm install -g typescript
之後轉換後執行
PS C:\Users\redmaple\Desktop\typescript\01> tsc 01-helloword.ts
tsc : 無法辨識 'tsc' 詞彙是否為 Cmdlet、函數、指令檔或可執行程式的名稱。請檢查名稱拼字是否正確,如果包含路徑的話,請確認路徑是否正確,然後再試一次。
位於 線路:1 字元:1
+ tsc 01-helloword.ts
+ ~~~
+ CategoryInfo : ObjectNotFound: (tsc:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\redmaple\Desktop\typescript\01> node -v
v22.18.0
PS C:\Users\redmaple\Desktop\typescript\01> npm install -g typescript
added 1 package in 2s
npm notice
npm notice New major version of npm available! 10.9.3 -> 11.5.2
npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.5.2
npm notice To update run: npm install -g npm@11.5.2
npm notice
PS C:\Users\redmaple\Desktop\typescript\01> npm install -g typescript
changed 1 package in 703ms
PS C:\Users\redmaple\Desktop\typescript\01> tsc 01-helloword.ts
PS C:\Users\redmaple\Desktop\typescript\01> node 01-helloword.js
Hello, World!
4.Typescript 類型
基本語法
let 變數名稱: 資料型別 = 初始值;
常見資料型別範例
let isDone: boolean = true; // 布林值
let age: number = 25; // 數字
let firstName: string = "John"; // 字串
let colors: string[] = ["red", "blue", "green"]; // 字串陣列
let anything: any = "hello"; // 任意型別(不建議常用)
一些練習
let found : boolean = true;
let grade : number = 3;
let firstName : string = "John";
let lastName : string = "Doe";
console.log('this is a ' + found +' answer');
console.log('my grade is ' + grade);
console.log(`my name is ${firstName} ${lastName}`);
// 使用 反引號 `。
// 透過 ${變數} 直接把變數值插入字串。
// 空格可以直接打在字符串中(${firstName} ${lastName})。
// 優點:
// 可讀性高。
// 多變數、多行字串更方便。
// 不需要手動加 +。
console.log('my name is ' + firstName + ' ' + lastName);
// 使用 單引號 ' '(或雙引號 " ")。
// 用 + 把字串和變數串接。
// 空格必須手動加 ' '。
// 優點:
// 所有
// 缺點:
// 當變數很多時,可讀性差。
// 容易漏加空格。
Visit the link for more information:
References