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

TypeScript中Buffer.toString传参报错:期望0个参数却传入1个

Buffer.toString()传参触发TypeScript类型错误的解决

问题详情

我编写了以下TypeScript代码:

const y = Buffer.from("fds")
y.toString("hex")

但tsc在"hex"参数处抛出类型错误:Expected 0 arguments, but got 1.

Node.js的Buffer.toString方法明明支持传入编码等参数,但当前TypeScript的类型定义似乎存在问题。

环境信息

  • Node.js版本:v20.12.2
  • TypeScript版本:5.3.2
  • 编译命令:
    yarn run tsc --noEmit --p ./src --incremental
    

配置文件

./src/tsconfig.json:

{
  "extends": "../tsconfig.base.json",
  "include": ["./src/**/*", "./mmmEval"],
  "exclude": ["node_modules", "_build", "dist"],
  "compilerOptions": {
    "target": "es2020",
    "composite": true,
    "module": "ESNext",
    "baseUrl": "./src",
    "paths": {
      "#src/*": ["./*"]
    },
    "types": ["node"],
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "plugins": [{ "name": "grats-ts-plugin" }]
  },
  "grats": {
    "graphqlSchema": "./src/gql/schema.generated.graphql",
    "tsSchema": "./src/gql/schema.generated.ts",
    "tsSchemaHeader": "// @ts-nocheck\n // This file was automatically generated and should not be edited.\n",
    "nullableByDefault": false
  },
}

tsconfig.base.json:

{
  "compilerOptions": {
    "composite": true,
    "target": "es2022",
    "lib": ["es2022", "dom", "dom.iterable", "esnext.disposable", "ESNext.Disposable"],
    "module": "CommonJS",
    "preserveSymlinks": true,

    "preserveValueImports": true,
    "ignoreDeprecations": "5.0",

    "noUnusedLocals": true,
    "esModuleInterop": false,
    "forceConsistentCasingInFileNames": true,
    "noPropertyAccessFromIndexSignature": true,
    "noUncheckedIndexedAccess": true,
    "strict": true,
    "skipLibCheck": true,
    "importsNotUsedAsValues": "error",
    "noFallthroughCasesInSwitch": true,
    "isolatedModules": true
  }
}

解决方法

1. 更新@types/node至兼容版本

问题大概率是@types/node版本与Node.js v20不匹配,导致类型定义未正确包含Buffer.toString的参数签名。执行以下命令更新:

yarn add -D @types/node@20.x

指定20.x版本可确保与Node.js v20完全兼容,避免版本差异带来的类型问题。

2. 检查类型加载配置

  • 确认tsconfig中的types字段已包含"node":你的配置中已经设置,这部分没问题。
  • 如果存在typeRoots配置,确保其包含node_modules/@types,否则TypeScript可能无法找到@types/node的类型定义。若未配置typeRoots,则无需额外操作,TypeScript会自动扫描该目录。

3. 排查类型冲突

若更新后问题仍存在,检查项目中是否有其他库或自定义类型覆盖了Buffer的类型定义。可以临时关闭skipLibCheck: true(在tsconfig.base.json中修改),重新编译看是否有类型冲突的提示,定位到冲突源后再处理。处理完成后建议重新开启skipLibCheck以提升编译速度。


内容的提问来源于stack exchange,提问作者rasen58

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 19:06:16