Search code examples
javatypescriptcode-translation

Translate Typescript to Java


I'm trying to change a code that is in Typescript into Java. I really don't know much about Typescript and got stuck on this function. I reduced the code into a simpler case. In this case CustomType1 and CustomType2 are just custom "export types" (which I implemented in Java as classes).

proof(): CustomType1 | 'given' | undefined {
    if (something) {
        return 'given'
    }

    const evidence = ... //Set to a new "instance" of CustomType2
    return evidence ? function(evidence) : undefined //Function returns an "instance" of CustomType1
}

Then, the previous code is run at some point like this

const proof = proof()
if (!proof || proof === 'given') {
    //...
}

I would appreciate if someone explains to me, how does this code on Typescript works.

What does the ? stand for? And what does the proof() function returns... an instance of Customtype1? the string "given"? both? And finally, when calling !proof, what does it stand for? because I don't see any boolean value in any part.


Solution

    1. Q: What does ? stand for?

      A: It is a ternary operator.

    2. Q: What does the proof() function return?

      A: It returns any one of the following: a CustomType1, the literal string 'given', or undefined. Specifically, it is a union.

    3. Q: When calling !proof, what does it stand for?

      A: Note that something tricky is going on in your example code. The local variable const proof is shadowing, i.e. replacing in the current scope, the original prooffunction. The code would be more clearly written as

       const result = proof()
       if (!result || result === 'given') {
           //...
       }
      

      This code is mostly functionally equivalent. Here, !result is true if result is a falsey value. Most pertinent to this case, it's true if result === undefined