Skip to content

Latest commit

 

History

History
59 lines (41 loc) · 2.33 KB

one-var-one-type.md

File metadata and controls

59 lines (41 loc) · 2.33 KB

Item 19: Use Different Variables for Different Types

Things to Remember

  • While a variable's value can change, its type generally does not.
  • To avoid confusion, both for human readers and for the type checker, avoid reusing variables for differently typed values.

Code Samples

let productId = "12-34-56";
fetchProduct(productId);

productId = 123456;
// ~~~~~~ Type 'number' is not assignable to type 'string'
fetchProductBySerialNumber(productId);
//                         ~~~~~~~~~
// Argument of type 'string' is not assignable to parameter of type 'number'

💻 playground


let productId: string | number = "12-34-56";
fetchProduct(productId);

productId = 123456;  // OK
fetchProductBySerialNumber(productId);  // OK

💻 playground


const productId = "12-34-56";
fetchProduct(productId);

const serial = 123456;  // OK
fetchProductBySerialNumber(serial);  // OK

💻 playground


const productId = "12-34-56";
fetchProduct(productId);

{
  const productId = 123456;  // OK
  fetchProductBySerialNumber(productId);  // OK
}

💻 playground