是否可以在TypeScript中声明编译错误?

时间:2017-06-12 11:56:42

标签: typescript assert

例如在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())}
""")

2 个答案:

答案 0 :(得分:1)

It is not a feature of Scala, it's a feature of ScalaTest which uses scala compiler at runtime as a library.

You can use typescript compiler as a library, it has rather complicated API documented here.

I have a node module published on github that simplifies things a bit, you can use it like this:

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);

(using assert from chai module)

答案 1 :(得分:0)

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

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

请注意,如果您不小心,此评论将使您破事,例如即使编译器允许您使用上面的示例,也不要使用y