Skip to content

Latest commit

 

History

History
64 lines (47 loc) · 2.29 KB

number-index.md

File metadata and controls

64 lines (47 loc) · 2.29 KB

Item 17: Avoid Numeric Index Signatures

Things to Remember

  • Understand that arrays are objects, so their keys are strings, not numbers. number as an index signature is a purely TypeScript construct designed to help catch bugs.
  • Prefer Array, tuple, ArrayLike, or Iterable types to using number in an index signature yourself.

Code Samples

interface Array<T> {
  // ...
  [n: number]: T;
}

💻 playground


const xs = [1, 2, 3];
const x0 = xs[0];  // OK
const x1 = xs['1'];  // stringified numeric constants are also OK

const inputEl = document.getElementsByTagName('input')[0];
const xN = xs[inputEl.value];
//            ~~~~~~~~~~~~~ Index expression is not of type 'number'.

💻 playground


const keys = Object.keys(xs);
//    ^? const keys: string[]

💻 playground


function checkedAccess<T>(xs: ArrayLike<T>, i: number): T {
  if (i >= 0 && i < xs.length) {
    return xs[i];
  }
  throw new Error(`Attempt to access ${i} which is past end of array.`)
}

💻 playground


const tupleLike: ArrayLike<string> = {
  '0': 'A',
  '1': 'B',
  length: 2,
};  // OK

💻 playground