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

新TypeScript项目中Zod报错:私有标识符仅支持ES2015及以上

问题描述

我通过以下步骤创建了一个新TypeScript项目:

mkdir zod-ts
cd zod-ts
npm init # 全部默认选项
npx tsc init

生成的tsconfig.json核心配置如下:

{
  "target": "es2016",
  "module": "commonjs",
  "strict": true,
  "esModuleInterop": true,
  "skipLibCheck": true,
  "forceConsistentCasingInFileNames": true
}

随后执行npm install zod @types/node typescript安装Zod及相关依赖,创建index.ts文件并编写如下代码:

import { z } from "zod";
const myType = z.object({
    myprop: z.string().optional(),
});

console.log(myType);

运行tsc index.ts时出现报错:

node_modules/zod/lib/types.d.ts:777:5 - error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher.

我已设置skipLibCheck: true,原本以为会忽略该错误,但并未生效,请问哪里操作有误?

问题解决

问题出在编译命令的使用方式上:当你直接用tsc index.ts指定单个文件编译时,TypeScript不会自动加载项目根目录的tsconfig.json,而是使用默认编译配置,所以你设置的skipLibCheck: true根本没起作用,同时默认的target版本可能低于ES2015,才会触发私有标识符的报错。

解决方法有两种:

  • 直接在项目根目录运行tsc(不带任何文件名参数),TypeScript会自动读取当前目录的tsconfig.json,此时你的skipLibCheck和target配置都会生效。
  • 如果一定要指定编译单个文件,用命令强制加载配置文件:tsc --project tsconfig.json index.ts

另外补充一点:你的target已经设为es2016,本身是支持私有标识符的,只要正确加载配置,就算不开skipLibCheck也不会报这个错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:47:05