Self-referential Type in TypeScript

Viewed 1515

I currently have an object similar to the following in a Vue.js app that I'm trying to port over to TypeScript. Note this object's structure is dictated by the Vuex library:

const getters = {
  allUsers(state) {
    return state.users;
  },
  firstUser(_state, getters) {
    return getters.allUsers()[0]
  }
}

How can I provide the appropriate type for getters here in firstUser?

const getters = {
  allUsers(state: State) {
    return state.users;
  },
  firstUser(_state: State, getters: typeof getters) {
    return getters.allUsers()[0]
  }
}

Currently I get the following error:

[ts] 'getters' is referenced directly or indirectly in its own type annotation.

Update: @basarat determined you can make that error go away by renaming the argument.

const getters = {
  allUsers(state: State) {
    return state.users;
  },
  firstUser(_state: State, theGetters: typeof getters) {
    return theGetters.allUsers()[0]
  }
}

However, typeof getters ends up being any rather than the type of the getters object.

2 Answers
Related