Item 38: Avoid Repeated Parameters of the Same Type
要点
- Avoid writing functions that take consecutive parameters with the same TypeScript type.
- Refactor functions that take many parameters to take fewer parameters with distinct types, or a single object parameter.
- 避免编写接受连续具有相同 TypeScript 类型的参数的函数。
- 重构接受多个参数的函数,使其接受较少的参数且具有不同的类型,或者将这些参数合并为一个单一的对象参数。
正文
ts
drawRect(25, 50, 75, 100, 1)
ts
function drawRect(x: number, y: number, w: number, h: number, opacity: number) {
// ...
}
ts
interface Point {
x: number
y: number
}
interface Dimension {
width: number
height: number
}
function drawRect(topLeft: Point, size: Dimension, opacity: number) {
// ...
}
ts
drawRect({ x: 25, y: 50 }, { x: 75, y: 100 }, 1.0)
// ~
// Argument ... is not assignable to parameter of type 'Dimension'.
ts
interface DrawRectParams extends Point, Dimension {
opacity: number
}
function drawRect(params: DrawRectParams) {
/* ... */
}
drawRect({ x: 25, y: 50, width: 75, height: 100, opacity: 1.0 })