Self-referential Type in TypeScript

Currently the Vue.js object has an object similar to the following which I am trying to pass to TypeScript. Note that this object 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 an appropriate type for getters here at firstUser

?

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

      

I am currently getting the following error:

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

      

Update: @basarat decided that you can remove this error 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 any

, not the type of the object getters

.

+3


source to share


2 answers


I really can't figure out why you need to getters

act this way, but I'm assuming you know what you are doing.

This is a limitation of the TypeScript compiler: it will understand that a type getters

is recursive and give it a type any

. The only way to get around this is to have a type name for getters

and use that. How about a class?

class Getters {
  allUsers(state: State) {
    return state.users;
  }
  firstUser(_state: State, theGetters: Getters) {
    return theGetters.allUsers()[0]; // hey, a bug!
  }
}
const getters = new Getters();

      



Now this is typed correctly and even shows you a bug in your implementation firstUser

(which I think you are fixing by passing _state

in allUsers()

).

Hope it helps. Good luck.

+2


source


[ts] 'getters' refers directly or indirectly to a native type annotation.

There are two getters in scope. Parameter and variable. Change it.

Fixed



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

      

More details

There are other errors as well, but this is the one you asked for help with.

+2


source







All Articles