{"record":{"id":"64559b0ddcf51473","repo":"krahets/hello-algo","slug":"error-64559b","errorCode":null,"errorMessage":"索引越界","messagePattern":"索引越界","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"codes/typescript/chapter_array_and_linkedlist/my_list.ts","lineNumber":32,"sourceCode":"    /* 构造方法 */\n    constructor() {\n        this.arr = new Array(this._capacity);\n    }\n\n    /* 获取列表长度（当前元素数量）*/\n    public size(): number {\n        return this._size;\n    }\n\n    /* 获取列表容量 */\n    public capacity(): number {\n        return this._capacity;\n    }\n\n    /* 访问元素 */\n    public get(index: number): number {\n        // 索引如果越界，则抛出异常，下同\n        if (index < 0 || index >= this._size) throw new Error('索引越界');\n        return this.arr[index];\n    }\n\n    /* 更新元素 */\n    public set(index: number, num: number): void {\n        if (index < 0 || index >= this._size) throw new Error('索引越界');\n        this.arr[index] = num;\n    }\n\n    /* 在尾部添加元素 */\n    public add(num: number): void {\n        // 如果长度等于容量，则需要扩容\n        if (this._size === this._capacity) this.extendCapacity();\n        // 将新元素添加到列表尾部\n        this.arr[this._size] = num;\n        this._size++;\n    }\n","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/typescript/chapter_array_and_linkedlist/my_list.ts#L14-L50","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Narrow the index at the type level with a branded Index type and validate before get().","Runtime-check: if (i >= 0 && i < list.size()) list.get(i);.","Fix loop bounds to i < list.size().","Recompute size after every mutation."],"exampleFix":"// before\nfor (let i = 0; i <= list.size(); i++) fn(list.get(i)); // throws at i===size\n// after\nfor (let i = 0; i < list.size(); i++) fn(list.get(i));","handlingStrategy":"validation","validationCode":"function safeGet(list: MyList, i: number): number | null {\n  return i >= 0 && i < list.size() ? list.get(i) : null;\n}","typeGuard":"function isValidIndex(list: MyList, i: unknown): i is number {\n  return typeof i === 'number' && Number.isInteger(i) && i >= 0 && i < list.size();\n}","tryCatchPattern":"try {\n  const v = list.get(i);\n} catch (e) {\n  if (e instanceof Error && e.message === '索引越界') { /* bad index */ } else throw e;\n}","preventionTips":["Loop with i < list.size(), not i <= list.size().","Brand numeric indices (type Index = number & { __brand: 'Index' }) and validate before use.","Re-read size() after mutations.","Let TypeScript narrow, but still runtime-check ranges."],"tags":["data-structures","index-out-of-bounds","typescript","array"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}