CAFECA-IO / KnowledgeManagement

Creating, Sharing, Using and Managing the knowledge and information of CAFECA
https://mermer.com.tw/knowledge-management
MIT License
0 stars 1 forks source link

[KM] TypeScript Doc | The TypeScript Handbook - The Basics #313

Open jing12345678910 opened 2 weeks ago

jing12345678910 commented 2 weeks ago

File Title:

The Basics

文章位置:

*

KM Steps:

MerMer 連結:

*

jing12345678910 commented 2 weeks ago

https://www.typescriptlang.org/docs/handbook/2/basic-types.html

jing12345678910 commented 2 weeks ago

TypeScript 基礎

靜態型別檢查

jing12345678910 commented 2 weeks ago

非異常失敗

jing12345678910 commented 2 weeks ago

類型工具

TypeScript 的型別系統不僅幫助靜態檢查,還能提升開發效率。例如,現代編輯器會透過 TypeScript 提供即時的提示與補全功能:

import express from "express";
const app = express();

app.get("/", (req, res) => {
  res.send // 提示所有可能的方法,如 send、sendFile 等。
});

jing12345678910 commented 2 weeks ago

TypeScript 編譯器——tsc

TypeScript 的核心工具是 tsc 編譯器,它能將 .ts 檔案轉換為標準的 JavaScript 檔案。例如:

// hello.ts
console.log("Hello, TypeScript!");

執行以下命令:

tsc hello.ts

生成的 hello.js 檔案如下:

console.log("Hello, TypeScript!");

即使原始程式碼出現型別錯誤,tsc 預設仍會產出對應的 JavaScript 檔案。


jing12345678910 commented 2 weeks ago

報錯時仍產出文件

預設情況下,即使 TypeScript 偵測到型別錯誤,tsc 仍會輸出編譯結果。但我們可以透過 --noEmitOnError 參數來避免這種情況:

tsc --noEmitOnError hello.ts

當啟用此設定後,若編譯過程中有錯誤,則不會輸出對應的 JavaScript 檔案。


jing12345678910 commented 2 weeks ago

顯式類型

雖然 TypeScript 具有型別推斷功能,但我們仍然可以明確指定變數的類型。例如:

function greet(person: string, date: Date) {
  console.log(\`Hello ${person}, today is ${date.toDateString()}!\`);
}

greet("Maddison", new Date());

jing12345678910 commented 2 weeks ago

擦除類型

TypeScript 只在編譯期間檢查型別,而在生成的 JavaScript 中會移除這些型別註解。例如:

TypeScript 程式碼:

function greet(person: string, date: Date) {
  console.log(\`Hello ${person}, today is ${date.toDateString()}!\`);
}

編譯後的 JavaScript:

function greet(person, date) {
  console.log("Hello " + person + ", today is " + date.toDateString() + "!");
}

jing12345678910 commented 2 weeks ago

降級

TypeScript 會將較新的 ECMAScript 語法轉換為目標 ECMAScript 版本。例如,模板字串會被降級為字串拼接:

console.log(\`Hello ${person}\`);

降級為:

console.log("Hello " + person);

我們可以透過 --target 選項指定目標版本,例如:

tsc --target es2015 hello.ts

jing12345678910 commented 2 weeks ago

嚴格性

TypeScript 提供多種嚴格性設定,例如:

noImplicitAny

若未顯式指定型別,TypeScript 預設會將變數型別視為 any。啟用此選項後,任何隱含為 any 的變數都會導致錯誤。

strictNullChecks

預設情況下,nullundefined 可以賦值給任何變數。啟用此選項後,TypeScript 會強制開發者處理 nullundefined 的情況,減少因疏忽導致的錯誤。