dsherret / dsherret/ts-morph

findOrCreate like functionality

Open
#1,682 0 comments 0 reactions 0 assignees View on GitHub
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.**

My use case is that I want to update a type definitions file on a file watcher. Pseudo-code-ish:

```typescript
watch(
glob("./public/locales/en/*.json"),
(files) => {
const project = new Project();
// here is where the problem tends to be:
const source = project.addSourceFileAtPathIfExists(typeDefs) ?? project.createSourceFile(typeDefs);
}
)
```

Then, I have to basically go through the entire chain like that, repeating it
```typescript
const i18nModule = source.getModule("'i18next'") ?? source.addModule("'i18next'");
const i18nInterface = i18nModule.getInterface("CustomTypeOptions") ?? i18nModule.createInterface("CustomTypeOptions");
const resources = i18nInterface.getProperty("resources") ?? i18nInterface.createProperty("resources");

const node = resources.getTypedNodeOrThrow().asKindOrThrow(SyntaxKind.TypeLiteral);
```

Frankly, it's quite tedious to do this for each iteration of the AST

**Describe the solution you'd like**

it would be nice if the `get*` and `add*` also had some sort of `upsert*` or `findOrCreate*`. For example, if I rewrote the above example:

```
const resources = project.getOrCreateSourceFile(typeDefs)
.getOrCreateModule("'i18next'")
.getOrCreateInterface("CustomTypeOptions")
.getOrCreateProperty("resources")
.getTypedNodeOrThrow()
.asKindOrThrow(SyntaxKind.TypeLiteral);
```

**Describe alternatives you've considered**

I basically made a wrapper function and did a functional composition, but it wasn't incredibly efficient

Contributor guide

Open the contributing guide

Research direction

Read CONTRIBUTING.md first, then trace the existing get* and add* APIs used for source files, modules, interfaces, and properties. Define how find-or-create behavior should work consistently across this chain, including repeated watcher iterations, and verify that the resulting API supports the example without breaking existing get* or add* behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.