一、TypeScript 与 JavaScript 的关系及核心理念
TS是JS的超集,JS能实现的TS都能实现,TS 最终是编译为 JS 去运行;(vue3就是用ts重构的)
JavaScript 动态类型(运行时确定类型)
TypeScript 静态类型(编译时检查类型)强类型,编码时指定类型;
二、TypeScript 基础
2.1 变量声明与类型注解
// 基本类型 四种
let username: string = "Alice";
let age: number = 30;
let isAdmin: boolean = true;
let dynamicValue: any = "Can be anything";
// 数组
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Bob", "Charlie"];
// 元组 可以存储不同类型数据
let userInfo: [string, number] = ["Alice", 30];
// 枚举
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING"
}
2.2 数组操作
// 创建数组
const fruits: string[] = ["Apple", "Banana"];
// 添加/删除元素
fruits.push("Orange"); // 末尾添加
fruits.pop(); // 删除最后一个
fruits.unshift("Mango");// 开头添加
fruits.shift(); // 删除第一个
// 数组遍历
fruits.forEach(fruit => console.log(fruit));
// 数组转换
const lengths = fruits.map(fruit => fruit.length);
// 数组过滤
const longFruits = fruits.filter(fruit => fruit.length > 5);
2.3 函数定义
// 基本函数
function add(a: number, b: number): number {
return a + b;
}
// 箭头函数
const multiply = (a: number, b: number): number => a * b;
// 可选参数
function greet(name: string, title?: string): string {
return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
// 默认参数
function createUser(name: string, role: string = "user") {
return { name, role };
}
2.4 接口与类型
// 接口定义
interface User {
id: number;
name: string;
email: string;
age?: number; // 可选属性
}
// 类型别名
type Point = {
x: number;
y: number;
};
// 实现接口
const user: User = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
2.5 类与面向对象
class Person {
// 成员变量
private id: number;
public name: string;
// 构造函数
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; // 常量
// 块级作用域
{
let inner = "visible inside block";
const SECRET = 123;
}
console.log(inner); // 报错
3.2 箭头函数
// 传统函数
function sum(a, b) {
return a + b;
}
// 箭头函数
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"}
`;
// 表达式嵌入
console.log(`Next year: ${age + 1}`);
3.4 解构赋值
ES6引入的一种从数组或对象中提取值,并赋值给变量的语法特性。
// 数组解构
const numbers = [1, 2, 3, 4];
const [first, second, ...rest] = numbers;//使用...语法收集剩余元素:
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// 对象解构
const user = { id: 1, name: "Bob", email: "bob@example.com" };
const { name, email } = user;
// 函数参数解构
function printUser({ name, email }) {
console.log(`${name} <${email}>`);
}
//对象参数
function getUserInfo({name, age}) {
return `${name} is ${age} years old`;
}
//带默认值的参数
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 扩展运算符
// 数组合并
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];//使用...语法收集剩余元素
// 对象合并
const defaults = { color: "red", size: "medium" };
const custom = { size: "large" };
const config = { ...defaults, ...custom };
//首先把 defaults 展开为 { color: "red", size: "medium" }
//然后再把 custom 展开为 { size: "large" },并覆盖前面的 size 值
//合并后变成:{ color: "red", size: "large" }
const config2 = { ...custom , ...defaults};
//...custom 展开为 { size: "large" }
//...defaults 展开为 { color: "red", size: "medium" }
//size 原本是 "large",但被 "medium" 覆盖
//合并后变成:{ color: "red", size: "medium" }
3.6 Promise 与异步
// 创建 Promise
const fetchData = () => new Promise((resolve, reject) => {
//模拟网络请求
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);
}
}
//当你在函数前加上 async,这个函数就会自动返回一个 Promise。
//await 只能在 async 函数中使用,它会等待 Promise 执行完成,拿到 resolve 的值。