function add(a: number, b: number): number { return a + b; }👎而不是这个:
// 堆代码 duidaima.com function add(a: any, b: any): any { return a + b; }2. 在 tsconfig.json 中启用“严格”模式
{ “compilerOptions”: { “strict”: true } }3.使用只读数组
const person: Readonly<{ name: string; age: number }> = { name: 'Alice', age: 30 }; person.age = 31; // Error: Cannot assign to 'age' because it is a read-only property const numbers: ReadonlyArray<number> = [1, 2, 3]; numbers.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'👎而不是这个:
const person = { name: 'Alice', age: 30 }; person.age = 31; // Allowed const numbers = [1, 2, 3]; numbers.push(4); // Allowed4. 使用解构来提取属性
function printPersonDetails({ name, age }: { name: string; age: number }) { console.log(`Name: ${name}, Age: ${age}`); }👎而不是这个:
function printPersonDetails(person: { name: string; age: number }) { console.log(`Name: ${person.name}, Age: ${person.age}`); }5. 数组泛型优于类型转换
const numbers: Array<number> = [1, 2, 3]; const firstNumber: number = numbers[0];👎而不是这个:
const numbers: any[] = [1, 2, 3]; const firstNumber: number = numbers[0] as number;6. 使用枚举作为常量
enum Fruit { APPLE = 'apple', BANANA = 'banana', ORANGE = 'orange', }👎而不是这个:
const FRUIT_APPLE = 'apple'; const FRUIT_BANANA = 'banana'; const FRUIT_ORANGE = 'orange';7. 对于对象形状,优先选择接口而不是类型别名
interface Person { name: string; age: number; }👎而不是这个:
type Person = { name: string; age: number; };8. 对可配置对象使用可选属性
interface Person { name: string; age?: number; }👎而不是这个:
interface Person { name: string; age?: number; }9. 使用 TypeScript 的实用类型
interface Person { name: string; age: number; address: string; } type PartialPerson = Partial<Person>; // Makes all properties optional type PersonName = Pick<Person, 'name'>; // Extracts a subset of properties type PersonWithoutAge = Omit<Person, 'age'>; // Removes a property10. 对多种可能的类型使用联合类型
function formatInput(input: string | number) { return `Input: ${input}`; }👎而不是这个:
function formatInput(input: string | number) { return `Input: ${input}`; }11.利用交叉类型来组合类型
interface Shape { color: string; } interface Circle { radius: number; } interface Rectangle { width: number; height: number; } type RedCircle = Shape & Circle; type RedRectangle = Shape & Rectangle; // 堆代码 duidaima.com const redCircle: RedCircle = { color: 'red', radius: 5 }; const redRectangle: RedRectangle = { color: 'red', width: 10, height: 20 };👎而不是这个:
interface Employee { name: string; age: number; } interface Manager { teamSize: number; } type EmployeeManager = Employee & Manager; const employee: EmployeeManager = { name: 'John Doe', age: 30, teamSize: 5 };12. 使用类型保护进行类型断言
function formatValue(value: string | number): string { if (typeof value === 'number') { return value.toFixed(2); } else if (typeof value === 'string') { return value.toUpperCase(); } else { throw new Error('Invalid value'); } }👎而不是这个:
function processValue(value: string | number): string { if (typeof value === 'number') { return value.toFixed(2); } else { return value.toUpperCase(); } }13.更喜欢函数式编程技术
const sum = Array.from({ length: 10 }, (_, i) => i + 1).reduce((acc, val) => acc + val, 0);👎而不是这个:
let sum = 0; for (let i = 1; i <= 10; i++) { sum += i; }14. 使用空合并运算符 (??)
const defaultValue = value ?? 'Default';👎而不是这个:
const defaultValue = value !== null && value !== undefined ? value : 'Default';15. 使用可选链接 (?.)
const username = user?.profile?.name;👎而不是这个:
const username = user && user.profile && user.profile.name;16.杠杆类型推断
const name = 'Alice';👎而不是这个:
const name: string = 'Alice';17.避免深层嵌套
function process() { // Code } if (condition1 && condition2 && condition3) { process(); }👎而不是这个:
if (condition1) { if (condition2) { if (condition3) { // Code } } }18.遵循一致的命名约定
添加注释来解释复杂的算法、重要的决策或边缘情况。避免仅仅重述代码的过多注释。