面试题答案
一键面试类型定义策略
- 明确和细化类型 在大型项目中,对于每个实体和操作都应定义清晰的类型。例如,在一个电商系统中,定义商品类型:
interface Product {
id: number;
name: string;
price: number;
description: string;
}
- 使用交叉类型和联合类型 交叉类型用于组合多个类型的特性,联合类型用于表示多种可能的类型之一。比如,一个函数可以接收字符串或数字类型的参数:
function printValue(value: string | number) {
console.log(value);
}
- 使用类型别名 为复杂类型创建别名,提高代码可读性。例如,在处理坐标时:
type Coordinate = [number, number];
function moveTo(coordinate: Coordinate) {
const [x, y] = coordinate;
console.log(`Moving to ${x}, ${y}`);
}
类型复用策略
- 接口继承 通过接口继承复用已有类型的属性和方法。如在一个图形绘制项目中:
interface Shape {
color: string;
}
interface Rectangle extends Shape {
width: number;
height: number;
}
- 泛型 泛型允许定义可复用的组件,适用于不同类型。例如,一个简单的数组包装类:
class Box<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
const numberBox = new Box<number>(10);
const stringBox = new Box<string>('hello');
类型检查策略
- 严格模式
启用严格模式(
strict: true
),TypeScript会进行更严格的类型检查。例如,严格模式下,未初始化的变量会报错。 - 使用
as const
对于对象字面量,使用as const
可以使类型推断为字面量类型,防止意外修改。如:
const color = 'red' as const;
// 此时color的类型为'red',而不是string
- 利用工具类型
如
Partial
、Required
、Readonly
等工具类型来辅助类型检查。例如,将一个类型的所有属性变为可选:
interface User {
name: string;
age: number;
}
type PartialUser = Partial<User>;
// PartialUser类型的对象,name和age属性都是可选的
通过以上这些策略,在大型TypeScript项目中可以有效地设计和管理复杂的类型系统,提高代码的可维护性和扩展性。