一、TypeScript 與 JavaScript 的關(guān)系及核心理念
TS是JS的超集,JS能實(shí)現(xiàn)的TS都能實(shí)現(xiàn),TS 最終是編譯為 JS 去運(yùn)行;(vue3就是用ts重構(gòu)的)
JavaScript 動(dòng)態(tài)類(lèi)型(運(yùn)行時(shí)確定類(lèi)型)
TypeScript 靜態(tài)類(lèi)型(編譯時(shí)檢查類(lèi)型)強(qiáng)類(lèi)型,編碼時(shí)指定類(lèi)型;
二、TypeScript 基礎(chǔ)
2.1 變量聲明與類(lèi)型注解
// 基本類(lèi)型 四種
let username: string = "Alice";
let age: number = 30;
let isAdmin: boolean = true;
let dynamicValue: any = "Can be anything";
// 數(shù)組
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Bob", "Charlie"];
// 元組 可以存儲(chǔ)不同類(lèi)型數(shù)據(jù)
let userInfo: [string, number] = ["Alice", 30];
// 枚舉
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING"
}
2.2 數(shù)組操作
// 創(chuàng)建數(shù)組
const fruits: string[] = ["Apple", "Banana"];
// 添加/刪除元素
fruits.push("Orange"); // 末尾添加
fruits.pop(); // 刪除最后一個(gè)
fruits.unshift("Mango");// 開(kāi)頭添加
fruits.shift(); // 刪除第一個(gè)
// 數(shù)組遍歷
fruits.forEach(fruit => console.log(fruit));
// 數(shù)組轉(zhuǎn)換
const lengths = fruits.map(fruit => fruit.length);
// 數(shù)組過(guò)濾
const longFruits = fruits.filter(fruit => fruit.length > 5);
2.3 函數(shù)定義
// 基本函數(shù)
function add(a: number, b: number): number {
return a + b;
}
// 箭頭函數(shù)
const multiply = (a: number, b: number): number => a * b;
// 可選參數(shù)
function greet(name: string, title?: string): string {
return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
// 默認(rèn)參數(shù)
function createUser(name: string, role: string = "user") {
return { name, role };
}
2.4 接口與類(lèi)型
// 接口定義
interface User {
id: number;
name: string;
email: string;
age?: number; // 可選屬性
}
// 類(lèi)型別名
type Point = {
x: number;
y: number;
};
// 實(shí)現(xiàn)接口
const user: User = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
2.5 類(lèi)與面向?qū)ο?/h5>
class Person {
// 成員變量
private id: number;
public name: string;
// 構(gòu)造函數(shù)
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
// 方法
greet() {
return `Hello, I'm ${this.name}`;
}
// Getter
get userId(): string {
return `user-${this.id}`;
}
}
// 繼承
class Employee extends Person {
private position: string;
constructor(id: number, name: string, position: string) {
super(id, name);
this.position = position;
}
}
三、ES6 新特性
3.1 變量聲明
// let 和 const
let counter = 10; // 可重新賦值
const PI = 3.14159; // 常量
// 塊級(jí)作用域
{
let inner = "visible inside block";
const SECRET = 123;
}
console.log(inner); // 報(bào)錯(cuò)
3.2 箭頭函數(shù)
// 傳統(tǒng)函數(shù)
function sum(a, b) {
return a + b;
}
// 箭頭函數(shù)
const multiply = (a, b) => a * b;
// this 綁定
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // 正確綁定 this
}, 1000);
}
};
3.3 模板字符串
const name = "Alice";
const age = 30;
// 多行字符串
const bio = `
Name: ${name}
Age: ${age}
Status: ${age > 25 ? "Adult" : "Young"}
`;
// 表達(dá)式嵌入
console.log(`Next year: ${age + 1}`);
3.4 解構(gòu)賦值
class Person {
// 成員變量
private id: number;
public name: string;
// 構(gòu)造函數(shù)
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
// 方法
greet() {
return `Hello, I'm ${this.name}`;
}
// Getter
get userId(): string {
return `user-${this.id}`;
}
}
// 繼承
class Employee extends Person {
private position: string;
constructor(id: number, name: string, position: string) {
super(id, name);
this.position = position;
}
}
// let 和 const
let counter = 10; // 可重新賦值
const PI = 3.14159; // 常量
// 塊級(jí)作用域
{
let inner = "visible inside block";
const SECRET = 123;
}
console.log(inner); // 報(bào)錯(cuò)
// 傳統(tǒng)函數(shù)
function sum(a, b) {
return a + b;
}
// 箭頭函數(shù)
const multiply = (a, b) => a * b;
// this 綁定
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // 正確綁定 this
}, 1000);
}
};
const name = "Alice";
const age = 30;
// 多行字符串
const bio = `
Name: ${name}
Age: ${age}
Status: ${age > 25 ? "Adult" : "Young"}
`;
// 表達(dá)式嵌入
console.log(`Next year: ${age + 1}`);
ES6引入的一種從數(shù)組或?qū)ο笾刑崛≈?,并賦值給變量的語(yǔ)法特性。
// 數(shù)組解構(gòu)
const numbers = [1, 2, 3, 4];
const [first, second, ...rest] = numbers;//使用...語(yǔ)法收集剩余元素:
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// 對(duì)象解構(gòu)
const user = { id: 1, name: "Bob", email: "bob@example.com" };
const { name, email } = user;
// 函數(shù)參數(shù)解構(gòu)
function printUser({ name, email }) {
console.log(`${name} <${email}>`);
}
//對(duì)象參數(shù)
function getUserInfo({name, age}) {
return `${name} is ${age} years old`;
}
//帶默認(rèn)值的參數(shù)
function createUser({name = "Anonymous", role = "user"} = {}) {
return {name, role};
}
console.log(createUser()); // {name: "Anonymous", role: "user"}
console.log(createUser({name: "Admin"})); // {name: "Admin", role: "user"}
const user = {name: "Bob", age: 35};
console.log(getUserInfo(user)); // "Bob is 35 years old"
//交換變量
let a = 1;
let b = 2;
[a, b] = [b, a]; // 交換值
console.log(a); // 2
console.log(b); // 1
3.5 擴(kuò)展運(yùn)算符
// 數(shù)組合并
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];//使用...語(yǔ)法收集剩余元素
// 對(duì)象合并
const defaults = { color: "red", size: "medium" };
const custom = { size: "large" };
const config = { ...defaults, ...custom };
//首先把 defaults 展開(kāi)為 { color: "red", size: "medium" }
//然后再把 custom 展開(kāi)為 { size: "large" },并覆蓋前面的 size 值
//合并后變成:{ color: "red", size: "large" }
const config2 = { ...custom , ...defaults};
//...custom 展開(kāi)為 { size: "large" }
//...defaults 展開(kāi)為 { color: "red", size: "medium" }
//size 原本是 "large",但被 "medium" 覆蓋
//合并后變成:{ color: "red", size: "medium" }
3.6 Promise 與異步
// 創(chuàng)建 Promise
const fetchData = () => new Promise((resolve, reject) => {
//模擬網(wǎng)絡(luò)請(qǐng)求
setTimeout(() => Math.random() > 0.5 ?
resolve("Success!") : reject("Error!"), 1000);
});
// 使用 Promise
fetchData()
.then(data => console.log(data)) //用于處理成功情況
.catch(error => console.error(error));//用于處理失敗情況
// Async/Await
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
//當(dāng)你在函數(shù)前加上 async,這個(gè)函數(shù)就會(huì)自動(dòng)返回一個(gè) Promise。
//await 只能在 async 函數(shù)中使用,它會(huì)等待 Promise 執(zhí)行完成,拿到 resolve 的值。