gpt4 book ai didi

javascript - tsc编译时不报错

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:43 25 4
gpt4 key购买 nike

我在弄清楚一个神秘的情况时遇到了一些问题

我有一个 tsconfig 文件:

{
"compilerOptions": {
"outDir": "./built",
"allowJs": true,
"target": "es5"
},
"include": [
"./app/**/*.ts"
]
}

当我使用下面的代码执行 tsc 时,这显然是错误的:

const credentials = Config.blahblah
import Config from '../../../config'

我知道这是错误的,因为 Config 不是在使用之前导入的,而是在使用之后导入的。

如果我切换这两行,那么代码就会通过我的测试。但问题是,如果我保持上面的顺序(这应该会给我一个错误),并且当我这样做时

mocha --compilers ts:ts-node/register,tsx:ts-node/register app/**/index-test.ts

甚至

tsc

例如:

➜  GhostFaceRestful git:(exie/workon_typescript) ✗ mocha --compilers ts:ts-node/register,tsx:ts-node/register app/**/index-test.ts
➜ GhostFaceRestful git:(exie/workon_typescript) ✗

根本没有错误消息。这使得调试变得极其困难。我想知道我做错了什么?至少 tsc 应该告诉我在这种情况下存在编译错误?

最佳答案

那是因为这不是 TypeScript 错误,因为 ES6(我想还有 TypeScript)import 语句被提升。 (您可以通过运行 tsc 来验证这一点 - 它也不会报告错误。)

有趣的是,编译时,require 调用不会被提升。所以这个:

const credentials = Config.blahblah
import Config from '../../../config'

变成这样:

"use strict";
var credentials = Config.blahblah;
var Config = require('../../../config');

您应该会看到运行时错误:

TypeError: Cannot read property 'Config' of undefined

如果你想验证 ts-node 是否报告 TypeScript 编译错误,请使用明显的 TypeScript 错误;像这样的东西:

const n: number = "not-a-number";

关于javascript - tsc编译时不报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41527955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com