TypeScript中Generator用Spread语法在VS Code运行异常问题
The discrepancy between VS Code's Code Runner and ts-node in cmd boils down to how TypeScript is being compiled/executed in each environment, specifically around ES version targeting and iterable handling.
Root Cause
When you run your code in VS Code's Code Runner, it’s likely using the default TypeScript compiler (tsc) with an ES5 target. Here’s why that breaks things:
- ES5 doesn’t natively support generators or the spread operator on iterables. TypeScript transpiles
[...iterable]toArray.prototype.slice.call(iterable)for ES5. - Generator objects are not array-like (they lack a
lengthproperty and indexed elements), so callingsliceon them throws theTypeError: chain(...).slice is not a functionerror.
In contrast, ts-node defaults to targeting ESNext/ES2015+, which preserves the spread operator and natively supports generators as iterables. This is why it works correctly in cmd.
Fix 1: Update Your TypeScript Configuration
Ensure your tsconfig.json targets an ES version that supports generators and iterable spread:
- Create or edit your
tsconfig.jsonfile in the project root:{ "compilerOptions": { "target": "ES2015", // Or "ESNext" for latest features "module": "CommonJS", "strict": true, "esModuleInterop": true } } - Save the file. Code Runner will now use this configuration to compile TypeScript correctly.
Fix 2: Configure Code Runner to Use ts-node
Instead of relying on tsc + Node.js, make Code Runner execute TypeScript directly with ts-node (matching your cmd setup):
- Open VS Code settings (Ctrl+, or Cmd+).
- Search for Code Runner: Executor Map.
- Edit the TypeScript entry to use
ts-node:"code-runner.executorMap": { "typescript": "ts-node" }- If
ts-nodeis installed locally (not globally), usenpx ts-nodeinstead.
- If
- Save the settings. Now Code Runner will run your TypeScript code exactly like
ts-nodedoes in cmd.
Verification
After applying either fix, running your code in VS Code should produce the same output as cmd:
[ 'A', 'B', 'C', 'D' ]
Content of the question来源于stack exchange,提问作者Gilad Noy

