例如,在 Scala 中,可以执行以下操作(ScalaTest):
assertDoesNotCompile("val a: String = 1")
assertTypeError("val a: String = 1")
assertCompiles("val a: Int = 1")
TypeScript 世界中是否存在类似的东西?
Edit:
我的意思是上下文感知编译。例如这个问题的代码如何编写确保编译失败的 Scala 单元测试? https://stackoverflow.com/questions/20114298/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())}
""")
它不是 Scala 的功能,而是 ScalaTest 的功能,它在运行时使用 scala 编译器作为库。
你可以使用 typescript 编译器作为一个库,它有相当复杂的 API 记录here https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API.
我有一个节点模块发布在 github 上 https://github.com/fictitious/tsc-simple这稍微简化了事情,你可以像这样使用它:
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);
(使用断言来自柴模块 http://chaijs.com/api/assert/)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)