dsherret / dsherret/ts-morph

How to get object string index name?

Open
#1,572 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.**

Firstly, devcontainer to test a problem.
[https://codesandbox.io/p/sandbox/wpkrx7](https://codesandbox.io/p/sandbox/wpkrx7)

I struggled how to get name of string index of object type.
For example, for this type I want to extract `projectId` identifier.
```ts
type ProjectJobTypePeriodVal = {
[projectId: string]: {
name: string
duration: string
}
}
```

By debugging and search in sources I came to this solution
```
const indexType = type.getStringIndexType(); // expect this not undefined

const keyName = type.compilerType.checker
.getIndexInfosOfType(type.compilerType)[0]
.declaration.locals.keys()
.next().value;
// finally keyname is `projectId`
```

**Describe the solution you'd like**

I am expecting my solution is bad. Maybe I missed a proper function or approach?

**Describe alternatives you've considered**

My alternative described above.

Contributor guide

Open the contributing guide

Research direction

Start with the linked CodeSandbox reproduction and inspect the existing type.getStringIndexType() and checker.getIndexInfosOfType() calls shown in the issue. Compare the available public type APIs with the declaration.locals workaround; the work is done when a documented ts-morph approach can retrieve the string index identifier projectId without relying on compiler internals.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.