【TS入门笔记3---接口(interface)、 函数与泛型 、类与面向对象 】
TS入门笔记2
- TypeScript---接口(interface)、 函数与泛型 、类与面向对象
- 一、接口(interface)
- 1. 接口(interface):接口主要用于定义对象的形状,也就是规定对象需要具备的属性和方法。
- 二、函数与泛型
- 1. 函数:在 TypeScript 中,函数的参数和返回值都可以指定类型。
- 2. 泛型:泛型可以让函数或类支持多种数据类型,同时保持类型安全。增强代码复用性和类型安全,避免重复逻辑。
- 三、类与面向对象
- 1. 类:类是面向对象编程的核心概念,TypeScript 支持类的定义、继承、封装和多态等特性。
- 2. 面向对象特性
TypeScript—接口(interface)、 函数与泛型 、类与面向对象
一、接口(interface)
1. 接口(interface):接口主要用于定义对象的形状,也就是规定对象需要具备的属性和方法。
(1)核心作用
定义对象结构:强制对象必须符合特定的属性格式。
描述函数类型:定义函数的参数和返回值类型。
可扩展性:通过继承组合多个接口。
(2)定义对象结构
//Person例子
interface Person {name: string;age: number;sayHello(): void;
}const person: Person = {name: 'Alice',age: 25,sayHello() {console.log(`Hello, my name is ${this.name}.`);}
};//User例子
interface User {id: number;name: string;email?: string; // 可选属性readonly role: "admin" | "user"; // 只读属性
}// 使用接口约束对象
const alice: User = {id: 1,name: "Alice",role: "admin" // ✅ 符合接口定义
};alice.role = "user"; // ❌ 编译错误:role 是只读属性
(3)定义函数类型
interface SearchFunc {(source: string, keyword: string): boolean;
}// 实现接口的函数
const search: SearchFunc = (src, kw) => src.includes(kw);
(4)接口继承
interface Animal {name: string;move(): void;
}// 继承并扩展
interface Dog extends Animal {bark(): void;
}const myDog: Dog = {name: "Buddy",move() { console.log("Running..."); },bark() { console.log("Woof!"); }
};
(5) 接口 vs 类型别名(type)
二、函数与泛型
1. 函数:在 TypeScript 中,函数的参数和返回值都可以指定类型。
(1)基本标注
// 显式标注参数和返回值
function add(x: number, y: number): number {return x + y;
}// 箭头函数类型
const greet = (name: string): string => `Hello, ${name}!`;
(2)可选参数与默认值
function createUser(name: string, age?: number, country: string = "China") {// age 是可选参数,country 有默认值
}
(3) 剩余参数(Rest Parameters)
function sum(...numbers: number[]): number {return numbers.reduce((a, b) => a + b);
}
2. 泛型:泛型可以让函数或类支持多种数据类型,同时保持类型安全。增强代码复用性和类型安全,避免重复逻辑。
(1)泛型函数
// 定义泛型函数(T 是类型占位符)
function identity<T>(arg: T): T {return arg;
}// 调用方式
identity<string>("hello"); // 显式指定类型
identity(42); // 自动推断为 number
(2) 泛型约束
interface Lengthwise {length: number;
}// 约束 T 必须包含 length 属性
function logLength<T extends Lengthwise>(arg: T): void {console.log(arg.length);
}logLength("abc"); // ✅ length 是 3
logLength({ length: 5 }); // ✅
logLength(123); // ❌ number 没有 length
(3) 泛型接口
interface KeyValuePair<K, V> {key: K;value: V;
}const pair: KeyValuePair<string, number> = {key: "age",value: 30
};
(4) 泛型工具函数示例
// 通用 API 响应处理
interface ApiResponse<T> {code: number;data: T;message: string;
}async function fetchData<T>(url: string): Promise<ApiResponse<T>> {const response = await fetch(url);return response.json();
}// 使用示例
type UserData = { id: number; name: string };
const result = await fetchData<UserData>("/api/user/1");
console.log(result.data.name); // ✅ 类型安全
三、类与面向对象
1. 类:类是面向对象编程的核心概念,TypeScript 支持类的定义、继承、封装和多态等特性。
(1)类的定义
class Person {// 成员属性(需显式声明类型)name: string;private age: number; // 私有属性constructor(name: string, age: number) {this.name = name;this.age = age;}// 方法public greet(): string {return `Hello, I'm ${this.name}`;}// Getter/Setterget currentAge(): number {return this.age;}set updateAge(newAge: number) {if (newAge > 0) this.age = newAge;}
}const bob = new Person("Bob", 25);
console.log(bob.greet()); // ✅
// console.log(bob.age); // ❌ 私有属性无法访问
(2)修饰符
(3)继承与多态
class Animal {constructor(public name: string) {}move(distance: number = 0) {console.log(`${this.name} moved ${distance}m`);}
}class Snake extends Animal {// 重写父类方法override move(distance = 5) {console.log("Slithering...");super.move(distance); // 调用父类方法}
}const sam = new Snake("Sammy");
sam.move(); // 输出 "Slithering..." 和 "Sammy moved 5m"
(4)抽象类
// 抽象类(不可实例化)
abstract class Shape {abstract area(): number; // 抽象方法(子类必须实现)// 普通方法display() {console.log(`Area: ${this.area()}`);}
}class Circle extends Shape {constructor(private radius: number) { super(); }area(): number {return Math.PI * this.radius ** 2;}
}const circle = new Circle(3);
circle.display(); // 输出 "Area: 28.274333882308138"
(5)实现接口
interface ClockInterface {currentTime: Date;setTime(d: Date): void;
}class Clock implements ClockInterface {currentTime: Date = new Date();setTime(d: Date) {this.currentTime = d;}
}
(6)静态成员
class Logger {static instance: Logger;private constructor() {} // 私有构造函数(单例模式)static getInstance() {if (!Logger.instance) {Logger.instance = new Logger();}return Logger.instance;}log(message: string) {console.log(`[LOG] ${message}`);}
}const logger = Logger.getInstance();
logger.log("System started"); // [LOG] System started
2. 面向对象特性
封装:借助访问修饰符(如private、protected、public)来控制类成员的访问权限。
继承:通过extends关键字实现类的继承,子类能够继承父类的属性和方法。
多态:不同的子类可以对父类的方法进行重写,从而实现不同的行为。