4

For example in Scala one can do following (ScalaTest):

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

Does something similar exist in TypeScript world?

Edit:
I mean context-aware compilation. For example code from this question 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 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

4 Comments

I think Scala has some way with types to crash when the compiler resolves them. But yes, this case is not a Scala feature directly, Scala only allows to use compiler. Your library with few helper functions could do the same thing as ScalaTest. Thank you for answering :).
It occurred to me that your solution probably will work only without context, that's not what I meant. I'll update the question.
Then the answer is definitely no, nothing like scala macros exists in typescript.
@monnef it seems to me that this answer deserves an upvote. It seems that (at least for some situations) it is possible to assert compilation error using tsc-simple lib that artem shared
1

This isn't exactly your use case, but TypeScript 3.9 has the // @ts-expect-error comment which may be useful for people:

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

Note that this comment will let you break things if you are not careful, so e.g. you should not use y in the example above even though the compiler will let you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.