Skip to content

Latest commit

 

History

History
66 lines (47 loc) · 2.39 KB

same-type-params.md

File metadata and controls

66 lines (47 loc) · 2.39 KB

Item 38: Avoid Repeated Parameters of the Same Type

Things to Remember

  • 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.

Code Samples

drawRect(25, 50, 75, 100, 1);

💻 playground


function drawRect(x: number, y: number, w: number, h: number, opacity: number) {
  // ...
}

💻 playground


interface Point {
  x: number;
  y: number;
}
interface Dimension {
  width: number;
  height: number;
}
function drawRect(topLeft: Point, size: Dimension, opacity: number) {
  // ...
}

💻 playground


drawRect({x: 25, y: 50}, {x: 75, y: 100}, 1.0);
//                        ~
// Argument ... is not assignable to parameter of type 'Dimension'.

💻 playground


interface DrawRectParams extends Point, Dimension {
  opacity: number;
}
function drawRect(params: DrawRectParams) { /* ... */ }

drawRect({x: 25, y: 50, width: 75, height: 100, opacity: 1.0});

💻 playground