Home > Blockchain >  Why typescript value becomes of type "any"
Why typescript value becomes of type "any"

Time:02-19

So it seems that for some reason, not sure who's fault it is - typescript type is not being recognized...

As an example, I'm using "pinia@next" npm package, and here's a simple demo code:

(This is the only file in the folder together with single package installed npm install pinia@next)

import { defineStore, Store } from "pinia";

export type State = {
  anyProperty: string
};

export const useAccountStore = defineStore("account", {
  state: () => ({} as State),
});

var test = useAccountStore() as Store<"account", State>;

And in this piece of code:

  1. "useAccountStore" has a correct type enter image description here
  2. "StoreDefinition" type is a function that returns "Store" as a return type: enter image description here
  3. VS Code thinks it returns an "any" type:

enter image description here

  1. Even, when I explicitly cast it to "Store" type, it results in "any" enter image description here
  • VS Code version: 1.64.1
  • VS Code typescript version: 4.5.5

Any ideas what might be happening?

  • It doesn't seem to be an issue with package itself, as I haven't found any similar issues on the internet as well as on tutorials on YouTube I can see that people are getting strong type without any additional steps... Thus this must be an issue with my Typescript configuration/version or something?
  • I did upgrade my Visual Studio Code to latest version
  • In Visual Studio Code dev tools - I cannot see no warnings nor errors related with typescript

CodePudding user response:

Store is defined in pinia's types.js file as

export type Store<
  Id extends string = string,
  S extends StateTree = {},
  G /* extends GettersTree<S>*/ = {},
  // has the actions without the context (this) for typings
  A /* extends ActionsTree */ = {}
> = _StoreWithState<Id, S, G, A> &
  UnwrapRef<S> &
  _StoreWithGetters<G> &
  // StoreWithActions<A> &
  (_ActionsTree extends A ? {} : A) &
  PiniaCustomProperties<Id, S, G, A> &
  PiniaCustomStateProperties<S>

If any of these resolve to any then the whole thing does.

  • Related