javascript - tsc编译时不报错

标签 javascript typescript mocha.js tsc

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

我有一个 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/

相关文章:

node.js - 使用 mocha/superagent 测试本地 https 服务器

javascript - Javascript 中的动态 CSS 图像 URL

node.js - "Failed to get configuration"通过 Node 在 Mocha 测试中使用 Wolkenkit 客户端

sonarqube - 合并纽约市的报道

typescript - nestjs中添加什么request.login

css - 如何从同一模式内的选择下拉列表中选择选项时设置模式的边距

javascript - 为什么 Typescript 期望 fetch( )'s ` body` 属性为 ReadableStream<Uint8Array>?

javascript - 使用另一个数组的对象属性对数组进行排序

Javascript:为什么我的值不相等?

javascript - 如何将数据 append 到元素属性值