返回
手写代码巩固前端基础,高频面试题实战合集(二)
前端
2023-11-25 11:00:56
随着项目不断迭代,接口的结构也需要做出相应的调整。为了应对这种情况,我们可以借助类型系统来进行灵活的处理。类型系统可以帮助我们定义和验证数据的结构,从而确保代码的健壮性和可维护性。
1. 定义接口结构
首先,我们需要定义一个接口来我们期望的数据结构:
interface User {
id: number;
name: string;
email: string;
}
2. 使用类型别名
接下来,我们可以使用类型别名来简化对接口的引用:
type User = {
id: number;
name: string;
email: string;
};
3. 接口扩展
随着业务需求的变化,我们可能需要对接口进行扩展。例如,我们需要添加一个新的字段 avatar
:
interface User {
id: number;
name: string;
email: string;
avatar: string;
}
4. 可选属性
有些属性可能不是必填的,我们可以使用 ?
来声明它们为可选属性:
interface User {
id: number;
name: string;
email?: string;
avatar?: string;
}
5. 联合类型
当一个变量可以有多种类型时,我们可以使用联合类型来它:
type UserOrError = User | Error;
6. 函数类型
我们可以使用函数类型来描述函数的签名:
type GetUserById = (id: number) => Promise<User>;
7. 类型断言
有时,我们需要明确告诉编译器一个变量的类型,可以使用类型断言:
const user = {} as User;
8. 枚举类型
我们可以使用枚举类型来定义一组有限的常量:
enum UserStatus {
ACTIVE = 'active',
INACTIVE = 'inactive',
DELETED = 'deleted',
}
9. 类类型
我们可以使用类类型来定义具有属性和方法的对象:
class User {
constructor(id: number, name: string, email: string) {}
getId(): number {
return this.id;
}
}
10. 泛型
泛型允许我们创建可重用的代码,它可以适用于多种类型:
function map<T>(array: T[], callback: (item: T) => T): T[] {
return array.map(callback);
}
总结
通过使用类型系统,我们可以提高代码的健壮性、可维护性和可扩展性。本文介绍了 TypeScript 中一些常见的面向对象编程和类型系统概念,希望对你的前端开发之旅有所帮助。