【问题标题】:Is it possible to assert compilation error in TypeScript?是否可以在 TypeScript 中断言编译错误?
【发布时间】:2020-09-08 15:23:03
【问题描述】:

例如在 Scala 中可以执行以下操作 (ScalaTest):

assertDoesNotCompile("val a: String = 1")
assertTypeError("val a: String = 1")
assertCompiles("val a: Int = 1")

TypeScript 世界中是否存在类似的东西?

编辑:
我的意思是上下文感知编译。例如来自这个问题的代码How do I write a scala unit test that ensures compliation fails?:

import shapeless.test.illTyped

//this version won't even compile
illTyped("getIdx(C.Ooga)")

//We can have multiple enum unions exist side by side
import Union_B_C._
B.values().foreach {b => Union_B_C.getIdx(b) should be (b.ordinal())}
C.values().foreach {c => Union_B_C.getIdx(c) should be (c.ordinal() + 2)}

//Though A exists in some union type, Union_B_C still doesn't know about it,
// so this won't compile
illTyped("""
  A.values().foreach {a => Union_B_C.getIdx(a) should be (a.ordinal())}
""")

【问题讨论】:

    标签: typescript assert


    【解决方案1】:

    这不是 Scala 的一个特性,它是 ScalaTest 的一个特性,它在运行时使用 scala 编译器作为库。

    您可以将 typescript 编译器用作库,它有相当复杂的 API 文档 here

    我有一个节点模块published on github 可以稍微简化一下,你可以这样使用它:

    import {createCompiler, CompileResult} from 'tsc-simple';
    
    const compiler= createCompiler({defaultLibLocation:'node_modules/typescript/lib'});
    
    const r: CompileResult = compiler.compile('let x = 3 + 2');
    
    assert.lengthOf(r.diagnostics, 0);
    

    (使用来自chai module 的断言)

    【讨论】:

    • 我认为当编译器解析它们时,Scala 有一些方法会导致类型崩溃。但是,是的,这种情况不是直接的 Scala 特性,Scala 只允许使用编译器。您的带有少量辅助函数的库可以做与 ScalaTest 相同的事情。谢谢你的回答:)。
    • 我突然想到您的解决方案可能只能在没有上下文的情况下工作,这不是我的意思。我会更新问题。
    • 那么答案肯定是否定的,打字稿中不存在像scala宏这样的东西。
    • @monnef 在我看来,这个答案值得一票。似乎(至少在某些情况下)可以使用 artem 共享的 tsc-simple lib 断言编译错误
    【解决方案2】:

    这并不完全是您的用例,但 TypeScript 3.9 有 // @ts-expect-error 注释,可能对人们有用:

    const x = 5;
    // @ts-expect-error
    const y: string = x;
    

    请注意,如果您不小心,此评论会让您破坏事物,例如即使编译器允许,你也不应该在上面的例子中使用y

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      相关资源
      最近更新 更多