react-ast icon indicating copy to clipboard operation
react-ast copied to clipboard

Optional parameters

Open 1cedsoda opened this issue 1 year ago • 2 comments

I want to generate this code. notice the optional method paramter.

export class Client {
  constructor(axiosInstance?: AxiosInstance) {
  }
}

This is my tsx:

<Class named="Client">
  <ClassMethod name="constructor" params={[
    <Identifier typeAnnotation="AxiosInstance">
      axiosInstance
    </Identifier>
  ]}>
  </ClassMethod>
</Class>

This code was generated:

class Client {
  constructor(axiosInstance: AxiosInstance) {
  }
}

How do I generate optional method parameters?

It would be great if there were some kinds of docs or more examples on how to build common js/ts patterns.

1cedsoda avatar Feb 24 '24 14:02 1cedsoda

I'm sorry I don't have docs yet. The names follow the same names used by the babel ast so if you poke around you'll probably find it. You can also look at the typescript types to see the available options. One helpful resource is https://astexplorer.net.

Just make sure that @babel/parser is enabled with tsx and jsx support.

astexp 2024-02-24-142251_screenshot

clayrisser avatar Feb 24 '24 19:02 clayrisser

At the current moment it seems like it might not be supported. I can work on adding support for optional parameters.

There are 2 ways you can get around it in the meantime.

  1. Use an | undefined type.
  2. Use the <Smart /> component which basically let's you feed you code literally to it.

clayrisser avatar Feb 24 '24 19:02 clayrisser