优先使用类型推断的场景
- 简单变量初始化:当变量的类型可以从初始化值明显看出时,使用类型推断可减少冗余代码。
let num = 10; // 类型推断为number
- 函数返回值:如果函数返回值的类型能从函数体内部清晰推断,无需显式声明。
function add(a, b) {
return a + b;
}
// 类型推断add函数返回值为number类型
- 数组字面量:数组元素类型可从元素本身推断,无需显式声明。
let arr = [1, 2, 3]; // 类型推断为number[]
优先使用类型声明的场景
- 函数参数:明确函数参数类型能增强代码可读性,让调用者清楚参数要求。
function greet(name: string) {
return `Hello, ${name}!`;
}
- 复杂数据结构:如对象、接口等复杂类型,显式声明能避免潜在错误。
interface User {
name: string;
age: number;
}
let user: User = {
name: 'John',
age: 30
};
- 公共API或模块对外暴露的接口:清晰的类型声明有助于其他开发者理解和使用。
// 定义一个模块
export function calculate(a: number, b: number): number {
return a + b;
}