3

I'm trying to implement the following "macros" transformer in TypeScript. I'd like to expand a definition like:

class SourceClass {
    @lazy
    lazyProperty    : Map<number, string>       = new Map()
}

to:

class SourceClass {
    $lazyProperty   : Map<number, string>       = undefined

    get lazyProperty () : Map<number, string> {
        if (this.$lazyProperty !== undefined) return this.$lazyProperty

        return this.$lazyProperty = new Map()
    }

    set lazyProperty (value : Map<number, string>) {
        this.$lazyProperty = value
    }
}

And I want to make the $lazyProperty property to be available for the rest of the program (to be able to check the lazy value presence). So, for example, I'd like this code to typecheck correctly, even that $lazyProperty is generated in the "macros":

class SourceClass {
    @lazy
    lazyProperty    : Map<number, string>       = new Map()

    method () {
        if (this.$lazyProperty !== undefined) { ... }
    }
}

For that I need the transformation to happen before the type-checking stage in compiler's pipeline, which, as I figured out after some research, is not how the regular transformers works.

However, if I'm correct, there are various workarounds, the most advanced is ts-morph, but I'm looking for something that is compatible with ts-patch and preferable something that integrates well with the IDE language services.

Can someone experienced with this kind of transformers outline the implementation plan? Perhaps there's a working example somewhere? (there has to be one, macros transformation should be a quite common requirement).

So far what I found is something related to overriding the CompilerHost: https://stackoverflow.com/a/59147818/365104 but its far from complete example.

Thanks a lot!

3
  • 1
    Magically, I can't find our conversation with cronoik here anymore. Wonder why. @cronoik You wouldn't be removing it silently, right? Commented Jun 13, 2021 at 6:20
  • Your comments were removed by a moderator because such discussions shouldn't be held at SO. As already suggested previously, please open a discussion on meta. Commented Jun 13, 2021 at 10:58
  • Here ya go -- this works great! github.com/GoogleFeud/ts-macros Commented Sep 25, 2023 at 22:20

0

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.