ts-morph icon indicating copy to clipboard operation
ts-morph copied to clipboard

Read tuple element labels

Open jasonkuhrt opened this issue 3 years ago • 2 comments

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

For documentation purposes I would like to get access to the tuple element labels, if any. Example:

const a: (() => [someLabel:1]) = [1] 

Describe the solution you'd like

The function t.getTupleElements() could return more structured data. It currently just returns a Type. How about this:

interface TupleElementInfo {
  label: null | string
  type: Type
}

Describe alternatives you've considered

Given the current API maybe this would be consistent:

t.getTupleElementLabel()

But I find that weird since there's no guarantee that t is a tuple there...

jasonkuhrt avatar Mar 05 '22 13:03 jasonkuhrt

If you have the AST node, there is a way to get this by calling getElements() on the node: https://github.com/dsherret/ts-morph/blob/c494733a73abe4e2d65aa922d4fdbfd92b926ad3/packages/ts-morph/lib/ts-morph.d.ts#L8898

That said, from the type, it looks like there is a tuple type in the compiler and these methods could be exposed:

https://github.com/dsherret/ts-morph/blob/c494733a73abe4e2d65aa922d4fdbfd92b926ad3/packages/common/lib/typescript.d.ts#L2710-L2718

For now, you can get these by inspecting (I think):

(t.compilerType as ts.TupleType).labeledElementDeclarations

dsherret avatar Mar 06 '22 15:03 dsherret

Trying the latter (access through the compiler type - labeledElementDeclarations seems to be undefined. Is there a specific way to have it be defined?

const elements = type.getTupleElements();
console.log(type.getText()); // [width?: number, height?: number, depth?: number]
console.log((type.compilerType as ts.TupleType).labeledElementDeclarations); // undefined

Edit: accessing target works.

const labels = type.compilerType.target.labeledElementDeclarations;

Works a treat for Triplex!! ts-morph still coming up strong.

image

itsdouges avatar Apr 26 '23 06:04 itsdouges