krahets/hello-algo · error · Error

索引越界

Error message

索引越界

What it means

TypeScript variant of the MyList get(index): throws '索引越界' when index < 0 || index >= this._size. get() returns arr[index]; _size is the logical length, _capacity the allocated length, so valid reads are confined to [0, _size). The TS type signature (index: number): number gives compile-time help but cannot express the runtime bound, so the guard is still required.

Source

Thrown at codes/typescript/chapter_array_and_linkedlist/my_list.ts:32

    /* 构造方法 */
    constructor() {
        this.arr = new Array(this._capacity);
    }

    /* 获取列表长度(当前元素数量)*/
    public size(): number {
        return this._size;
    }

    /* 获取列表容量 */
    public capacity(): number {
        return this._capacity;
    }

    /* 访问元素 */
    public get(index: number): number {
        // 索引如果越界,则抛出异常,下同
        if (index < 0 || index >= this._size) throw new Error('索引越界');
        return this.arr[index];
    }

    /* 更新元素 */
    public set(index: number, num: number): void {
        if (index < 0 || index >= this._size) throw new Error('索引越界');
        this.arr[index] = num;
    }

    /* 在尾部添加元素 */
    public add(num: number): void {
        // 如果长度等于容量,则需要扩容
        if (this._size === this._capacity) this.extendCapacity();
        // 将新元素添加到列表尾部
        this.arr[this._size] = num;
        this._size++;
    }

View on GitHub (pinned to 69932aed18)

Solutions

  1. Narrow the index at the type level with a branded Index type and validate before get().
  2. Runtime-check: if (i >= 0 && i < list.size()) list.get(i);.
  3. Fix loop bounds to i < list.size().
  4. Recompute size after every mutation.

Example fix

// before
for (let i = 0; i <= list.size(); i++) fn(list.get(i)); // throws at i===size
// after
for (let i = 0; i < list.size(); i++) fn(list.get(i));
Defensive patterns

Strategy: validation

Validate before calling

function safeGet(list: MyList, i: number): number | null {
  return i >= 0 && i < list.size() ? list.get(i) : null;
}

Type guard

function isValidIndex(list: MyList, i: unknown): i is number {
  return typeof i === 'number' && Number.isInteger(i) && i >= 0 && i < list.size();
}

Try / catch

try {
  const v = list.get(i);
} catch (e) {
  if (e instanceof Error && e.message === '索引越界') { /* bad index */ } else throw e;
}

Prevention

When it happens

Trigger: Passing a number-typed value that is out of range (TS only checks shape, not range); off-by-one loop bounds; reading a stale index after remove(); get(0) on an empty list.

Common situations: Trusting the number type to imply validity; arithmetic that yields size as an index; porting JS code that relied on undefined returns instead of throws.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/64559b0ddcf51473. Report an issue: GitHub.