我可以在特定文件上运行 tsc 并自动包含 tsconfig.json 吗?

问题描述 投票:0回答:1

背景

我在同一目录中有一个 typescript 文件和 tsconfig.json:

index.ts:

function foo(bar) {
    bar.buzz = 100;
}

let obj = { x: 0 };
obj.bar = 100;

tsconfig.json:

{
    "compilerOptions": {
        "strict": true
    }
}

如果我运行

npx tsc -p tsconfig.json
,我会收到 2 个错误,这正是我所期望的。

如果我运行

npx tsc index.ts
,我只会收到 1 个错误。

我的问题

有没有办法运行

npx tsc index.ts
(或类似的)并让它获取 tsconfig 文件?

如果是这样,我该怎么做?

如果没有,为什么不呢?我是打字稿新手,并试图了解一切是如何连接的。

就其价值而言,从我对 tsconfig doc 的审查以及其他各种搜索来看,似乎您无法运行

npx tsc index.ts
并让它获取 tsconfig 文件。

尽管如此,让更有经验的人证实我的猜测会很有用。

(可选:其他详细信息)

环境详情:

$ node -v
v18.19.0
$ npx tsc -v
Version 5.3.3

操作系统:MacOS Catalina (10.15.7)

完整
tsc
命令输出

$ npx tsc index.ts
index.ts:6:5 - error TS2339: Property 'bar' does not exist on type '{ x: number; }'.

6 obj.bar = 100;
      ~~~


Found 1 error in index.ts:6
$ npx tsc -p tsconfig.json 
index.ts:1:14 - error TS7006: Parameter 'bar' implicitly has an 'any' type.

1 function foo(bar) {
               ~~~

index.ts:6:5 - error TS2339: Property 'bar' does not exist on type '{ x: number; }'.

6 obj.bar = 100;
      ~~~


Found 2 errors in the same file, starting at: index.ts:1
$ npx tsc
index.ts:1:14 - error TS7006: Parameter 'bar' implicitly has an 'any' type.

1 function foo(bar) {
               ~~~

index.ts:6:5 - error TS2339: Property 'bar' does not exist on type '{ x: number; }'.

6 obj.bar = 100;
      ~~~


Found 2 errors in the same file, starting at: index.ts:1
typescript tsconfig tsc
1个回答
0
投票

当您运行

npx tsc -p tsconfig.json
时,TypeScript 会编译
tsconfig.json
上下文中的所有文件,并应用其中指定的配置。这就是为什么您会看到两个错误,因为
strict
中的
tsconfig.json
选项强制执行更严格的类型检查。
您可以在 Jack Franklin “使用 TypeScript 和 ES 模块发布 Node 模块” 中查看示例。

但是,当您运行

npx tsc index.ts
时,TypeScript 仅编译
index.ts
不考虑 tsconfig.json
。这就是您只看到一个错误的原因;不应用 
strict
 选项。

目前,没有直接的方法可以在单个文件上运行

tsc

 并让它自动包含 tsconfig.json
 中的设置。当您指定文件时,
tsc
 会绕过 
tsconfig.json
 创建的项目上下文。

一种解决方法是使用项目引用或包含

tsconfig.json

 和您要编译的特定文件的构建脚本。例如,您可以创建一个脚本,在运行 
tsconfig.json
 之前,将 
index.ts
 更改为仅在 
"files"
 数组
中包含
tsc

您还应该更新

index.ts

 来修复错误:

interface Bar { buzz?: number; } function foo(bar: Bar) { bar.buzz = 100; } let obj = { x: 0, bar: 100 };
    
© www.soinside.com 2019 - 2024. All rights reserved.