dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
5k stars 195 forks source link

[question] Identifying the concrete source of a reference #1197

Open myndzi opened 3 years ago

myndzi commented 3 years ago

Hi there. I'm stumbling through trying to use ts-morph to generate some code from an interface. One thing I'm hoping to do is essentially annotate fields in the interface to guide some of the implementation. It seems like wrapping in a generic type reference would be a fairly ergonomic way to do this.

For example:

// type Annotated<T> = T
import type { Annotated } from 'mylib';

interface Foo {
  name: Annotated<string>
}

One thing I'm struggling to figure out is how to determine if "Annotated" is the actual type I am providing, or just happens to have the same name as something the user defined. It seems like I might be able to find my way there through something like:

interfaceDeclaration.getProperties().map(prop => {
    const node = prop.getTypeNode();
    if (node.getKind() === SyntaxKind.TypeReference) {
        const sourceFile = n.getSourceFile();
        // there seems to maybe be the information I need to make a distinction here?
    }
});

However, I'm not entirely sure if this is a reasonable approach, and I can't seem to determine the methods that tell me concretely "in this context, Annotated is a reference to the type I've provided".

Is there a better way to approach this? If this is the best approach, what methods am I looking for to decide affirmatively that I "care" about this type?

(also, is there an IRC channel or Discord where I could go for help as I work through this stuff?)

douglasg14b commented 1 month ago

You ever figure this out?

myndzi commented 1 month ago

Nope, I gave up.

douglasg14b commented 1 month ago

Damn, that's brutal. 😔

myndzi commented 1 month ago

Well when I say "gave up", it was just a hobby thing that I didn't pursue further. My condolences if you're here for some work-related effort 😅

These days I use Typebox, which is reasonably performant and has a bunch of methods that basically map to Typescript operations. You can define a JS object and derive a type from it, and the validation function serves as a type guard. So I've solved my desire to have one source of truth for defining Typescript types and also validation logic in that way.

(once the data is known to conform to the type, I can write whatever other functions I want, after all)

douglasg14b commented 1 month ago

Yeah, I'm trying to parse out some types. And resolve imported types to their concrete definitions. I know it's possible, but cannot figure out how.

Thanks!