Direct access to object key from type

Viewed 45

Considering the following interface :

interface StateEntry {
    [state: string]: {metaState: string}
}

With objects always having the same shape such as :

{NEW: {metaState: "ACTIVE"}}

I have an array of such objects (such as const arr = [state1, state2, state3], how can I directly access the unique state value from arr[0]?

Something as arr[0].state === 'NEW'

I think doing Objects.keys(arr[0])[0] is fairly unelegant.

Should I change the interface ?

3 Answers

Use For..each to iterate the array and For..in to iterate each object

Ex: For..in loop.

For(const key in arrayName) => console.log(key)

Assuming there is only one key per entry object, you may change your interface:

interface StateEntry {
    type: string
    metaState: string
}

The value would be:

{ type: "NEW", metaState: "ACTIVE" }

Accessing the type would be:

arr[0].type

You can do:

Object.keys(arr[0])[0]

for your example


interface StateEntry {
  [state: string]: { metaState: string }
}
const state1: StateEntry = { NEW: { metaState: "ACTIVE" } }
const state2: StateEntry = { NEW: { metaState: "ACTIVE" } }

const arr: StateEntry[]= [state1,state2]

console.log(Object.keys(arr[0])[0])

full example in TypeScript playGround

Related