request for `PrintHandler` support in `printNode`
- Dominant language
- TypeScript
- Stars
- 6.2k
- Forks
- 238
- Avg merge
- 2m
- Merged PRs (30d)
- 1
Description
**Is your feature request related to a problem? Please describe.**
`PrintHandlers` are a powerful option in ts printers enabling users to modify the print results. Today ts-morph doesn't support this and the transformation support is experimental. If users want to print modified AST they need to rely on the typescript compiler API. A small change to `printNode` could significantly improve this.
**Describe the solution you'd like**
`ts.createPrinter` supports two sets of options. The first [is supported today](https://github.com/dsherret/ts-morph/blob/latest/packages/ts-morph/src/utils/compiler/printNode.ts#L6). The second, [handlers](https://github.com/microsoft/TypeScript/blob/main/src/compiler/types.ts#L9780), is not.
I'd like `printNode` to accept an interface similar to `PrintHandlers` which provides callbacks with ts-morph Nodes rather than ts.Node. For example:
```ts
substituteNode?(hint: EmitHint, node: tsMorph.Node): ts.Node;
```
**Describe alternatives you've considered**
Currently this can be achieved in projects by using `Node.compilerNode` to leave the ts-morph ecosystem and use the typescript compiler API directly. However, this presents a painful issue because any usage of `PrintHandlers.substituteNode` or `PrintHandlers.isEmitNotificationEnabled` or `PrintHandlers.onEmitNode` forces projects into one of two scenarios:
1. Ensure handlers have no ts-morph dependencies and can operate on just the typescript compiler API
2. Maintain their own mapping of typescript nodes to ts-morph nodes for the entire AST
Both of these options are impractical. (1) doesn't suit all use cases especially for `substituteNode` which often relies on linking previously analyzed nodes to visited nodes and (2) would be better served by exposing the ts-morph internal helpers such as `getNodeFromCompilerNode`
Contributor guide
Research direction
Start with packages/ts-morph/src/utils/compiler/printNode.ts and compare its supported ts.createPrinter options with the PrintHandlers definition in TypeScript's compiler types. Trace how ts-morph Nodes can be provided to the requested callbacks, then verify that printNode accepts the handlers and supports substituteNode, isEmitNotificationEnabled, and onEmitNode behavior without requiring callers to use compiler nodes directly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100