gpt4 book ai didi

typescript - 是否可以在 TypeScript 中断言编译错误?

转载 作者:行者123 更新时间:2023-12-04 16:09:50 26 4
gpt4 key购买 nike

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

最佳答案

这不是 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 的断言)

关于typescript - 是否可以在 TypeScript 中断言编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44498861/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com