TypeScript作为JavaScript的超集,不仅提供了基本的类型系统,还有许多强大的进阶特性。本文将深入探讨TypeScript的进阶概念,帮助你编写更健壮、可维护的代码,充分发挥TypeScript的潜力。
1. 函数重载 - 一个函数,多种用法
函数重载允许一个函数根据不同的参数类型和数量,有不同的行为。这在API设计中特别有用,可以为调用者提供更清晰的类型提示。
// 函数重载声明
function hello(name: string): string;
function hello(age: number): string;
// 函数实现(必须兼容所有重载)
function hello(value: string | number): string {
if (typeof value === 'string') {
return `你的名字是 ${value}`;
} else if (typeof value === 'number') {
return `你的年龄是 ${value}`;
} else {
return '请输入正确的参数';
}
}
// 使用
hello('小明'); // 返回: "你的名字是 小明"
hello(18); // 返回: "你的年龄是 18"
重点说明:
- 先写所有的重载声明(没有函数体)
- 最后写一个兼容所有重载的函数实现
- 实现函数的参数类型通常是联合类型
- TypeScript会根据传入的参数类型自动选择正确的重载
- 重载签名必须与实现签名兼容
2. 接口与继承 - 定义对象的"规范"
基本接口
接口是TypeScript中定义对象结构的核心方式,它描述了对象应该具有的属性和方法。
interface Person {
name: string;
age: number;
sayHello(): void;
readonly id: number; // 只读属性
address?: string; // 可选属性
}
// 使用接口
const person: Person = {
name: '小明',
age: 18,
id: 1001,
sayHello() {
console.log(`你好,我是${this.name}`);
}
};
接口继承
接口可以继承其他接口,获得父接口的所有属性和方法。
interface Person {
name: string;
age: number;
}
interface Student extends Person {
school: string;
grade: number;
}
// 使用继承的接口
const student: Student = {
name: '小明',
age: 18,
school: '清华大学',
grade: 1
};
接口合并
同名接口会自动合并,这是TypeScript的一个强大特性。
interface Box {
height: number;
width: number;
}
interface Box {
length: number;
color: string;
}
// 最终的Box接口包含所有属性
const box: Box = {
height: 10,
width: 20,
length: 30,
color: 'red'
};
3. 命名空间 - 组织和管理代码
命名空间用于将相关的代码组织在一起,避免命名冲突。
namespace BlogModule {
export interface Article {
title: string;
content: string;
}
export class BlogPost implements Article {
constructor(
public title: string,
public content: string,
public author: string
) {}
publish() {
console.log(`