kentcdodds / babel-plugin-macros

🎣 Allows you to build simple compile-time libraries
https://npm.im/babel-plugin-macros
MIT License
2.62k stars 135 forks source link

Are macros run before @babel/plugin-transform-typescript? #150

Closed vedantroy closed 4 years ago

vedantroy commented 4 years ago

Not sure this information is relevant, but here it is:

I am trying to create a macro that takes in type information and uses it to generate compile time checking of objects. An example:

interface Asteroid {
  type: 'asteroid'
  location: [number, number, number]
  mass: number
}

// the right hand side will be a function that accepts a object and validates that it is an asteroid
const validateAsteroid = createValidator(Asteroid)

Will the macro be aware that Asteroid is a typescript interface, or, will this information have already been stripped by the time the macro is executed?

I also realized that createValidator(Asteroid) is invalid Typescript syntax because the Typescript compiler complains that Asteroid is being used as a value. Are there any ways to call a macro with a Typescript type that avoid making IDEs complain? If not, I'd be willing to work on support for something like createValidator<Asteroid>() (or some alternative syntax), so that macros can accept Typescript types.

Update: After playing around here, I think I came to the conclusion that the Typescript type information is stripped after the macro is run, but, Asteroid is marked as an identifier in the abstract syntax tree, so, the macro cannot get any useful information out of it, which is unfortunate.

vedantroy commented 4 years ago

Nevermind, seems like making Typescript-aware macros is possible: https://github.com/vhfmag/tsguard.macro