dsherret / ts-morph

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

Get properties from ObjectType using an EcmaScript symbol instead of a string #1538

Open Melchyore opened 1 month ago

Melchyore commented 1 month ago

Is your feature request related to a problem? Please describe.

Hi.

I have a symbol called HEADERS, defined as follows:

export const HEADERS = Symbol.for('__headers')

I'm using this symbol to augment the type of a method:

ok<T, Instance extends this>(
  body: T,
  etag?: boolean
): {
  __response: T
  __status: GetStatus<Instance, 200>
  [HEADERS]: ReturnType<Instance['append']>
}

Now, when I read the AST of this method, I have access to the ObjectType, which is

{
  __response: T
  __status: GetStatus<Instance, 200>
  [HEADERS]: ReturnType<Instance['append']>
}

I want to get the [HEADERS] property using my symbol

type.getProperty(HEADERS)

But that's not possible, cuz the getProperty method accepts only a string as parameter or a function. For the latter, I did this and it worked

getProperty((property) =>
  property.getName().startsWith('__@HEADERS')
)

... but I wonder if it's possible to use only the symbol.

Describe the solution you'd like

The getProperty method should accept a symbol as parameter.

Describe alternatives you've considered

getProperty((property) =>
  property.getName().startsWith('__@HEADERS')
)

Is it possible to achieve this, please?

lazarljubenovic commented 1 month ago

How do you intend to use the Symbol itself? You can't really import things from the very code you're analyzing and expect object equalities there. It's the same logic as not being able to get AST of a function and then just .call it or something.

Melchyore commented 1 month ago

How do you intend to use the Symbol itself? You can't really import things from the very code you're analyzing and expect object equalities there. It's the same logic as not being able to get AST of a function and then just .call it or something.

Hey! Thanks for your answer.

Since Symbols are valid property keys, I thought it would be possible to get a property by a symbol.

So, I assume the only way to get it, is how I did it (i.e check if the name starts with __@HEADERS).

lazarljubenovic commented 1 month ago

They are valid keys in the code, but that doesn't mean you can use the symbol from the runtime of your code and expect it to work when inspecting that code's AST using a library like this. Functions can also be called, and yet having an AST of a function doesn't mean you can call it.