You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中Generator用Spread语法在VS Code运行异常问题

Why the Behavior Differs & How to Fix It

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] to Array.prototype.slice.call(iterable) for ES5.
  • Generator objects are not array-like (they lack a length property and indexed elements), so calling slice on them throws the TypeError: chain(...).slice is not a function error.

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:

  1. Create or edit your tsconfig.json file in the project root:
    {
      "compilerOptions": {
        "target": "ES2015", // Or "ESNext" for latest features
        "module": "CommonJS",
        "strict": true,
        "esModuleInterop": true
      }
    }
    
  2. 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):

  1. Open VS Code settings (Ctrl+, or Cmd+).
  2. Search for Code Runner: Executor Map.
  3. Edit the TypeScript entry to use ts-node:
    "code-runner.executorMap": {
      "typescript": "ts-node"
    }
    
    • If ts-node is installed locally (not globally), use npx ts-node instead.
  4. Save the settings. Now Code Runner will run your TypeScript code exactly like ts-node does 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:34:26