是否可以断言打字稿中的编译错误? [英] Is it possible to assert compilation error in TypeScript?

查看:0
本文介绍了是否可以断言打字稿中的编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

编辑:
我指的是上下文感知编译。例如问题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编译器用作库。

您可以使用TypeScrip编译器作为库,它有相当复杂的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的断言)

这篇关于是否可以断言打字稿中的编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆