#Using ts-morph to get a property from an anonymous type (object) using a symbol

21 messages · Page 1 of 1 (latest)

small elm
#

Hey! I'm using a symbol [HEADERS] as a key for an anonymous type:

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

Now, I'm using ts-morph, and I want to get the [HEADERS] property specifically. But I can't do it, the only way to get a property, is using the getProperty(name) and it accepts only a string. Is there any way to get a property by a symbol, please?

Thank you!

kind kernel
#

i know nothing about ts-morph so i might not actually be able to help, but: where does HEADERS come from exactly? it's got to be a literal-typed constant, right?

#

oh sorry i misread, you said it's a symbol. i understand the question now, but don't know the answer 😅

small elm
#

Thanks for your answer. Yup, it's a symbol:

const HEADERS = Symbol.for('HEADERS')
#

I can't find any way to get a property from an anonymous type using a symbol key in ts-morph

kind kernel
#

it looks like getProperty has some overloads. can you use one of the overload signatures where you pass in a callback to check?

quasi cradleBOT
#
/**
 * Gets a property or returns undefined if it does not exist.
 * @param name - By a name.
 */
getProperty(name: string): Symbol | undefined;
/**
 * Gets a property or returns undefined if it does not exist.
 * @param findFunction - Function for searching for a property.
 */
getProperty(findFunction: (declaration: Symbol) => boolean): Symbol | undefined;
/** @internal */
getProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined;
getProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined {
  return getSymbolByNameOrFindFunction(this.getProperties(), nameOrFindFunction);
}
kind kernel
#

getProperty(x => x === Symbol.for('HEADERS')) or somesuch

small elm
#

The Symbol they are referring to is not the EcmaScript Symbol 😦

kind kernel
#

yeah, i figured that. but does it not contain the property name? so getProperty(x => x.name === Symbol.for('HEADERS')) or whatnot (just totally guessing here)

quasi cradleBOT
#
getName() {
  return this.compilerSymbol.getName();
}
small elm
kind kernel
#

if you log x.getName() there, what do you see?

#

i wonder if there's some standard mangling/stringification scheme you can apply to RHS

small elm
#

This is what's printed: __@HEADERS@1347

kind kernel
#

heh, neat

#

again, just totally guessing here, but can you get the ts.Symbol for HEADERS and then use that to compare?

small elm
#

I assume I can do something like

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

But I want my symbol to be the only source of truth :/

small elm