Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Stores and State

Typing State with TypeScript

Type Pinia state with interfaces, as casts and return types, handle null and empty arrays, and see how the types flow to components. Includes a runnable JavaScript demo.

Pinia was written with TypeScript in mind. In most stores you do not need to write types at all: Pinia infers them from your state() function. You only help it in a few places, and this lesson shows exactly where.

The site cannot run a TypeScript compiler inside the browser pane here, so the type examples are read-only. The runnable demos show the same stores in plain JavaScript, where the logic is identical.

Inference does most of the work

Given this store, TypeScript already knows every type:

TypeScript
import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", {
  state: () => ({
    count: 0,
    label: "clicks",
  }),
  getters: {
    doubled: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++;
    },
  },
});

In a component, store.count is a number, store.label a string, store.doubled a number and store.increment a function with no parameters. Writing store.count = "x" is a compile error.

Where inference needs help

Inference works from the initial value. That fails when the initial value says too little:

  • [] becomes never[] (nothing can be pushed).
  • null becomes null (nothing else can be assigned).
  • An empty object {} hides the keys you plan to add.

There are two fixes. The first is a cast with as on the property:

TypeScript
interface User {
  id: number;
  name: string;
}

export const useUsersStore = defineStore("users", {
  state: () => ({
    list: [] as User[],
    current: null as User | null,
    loading: false,
  }),
});

The second is an interface for the whole state, with a return type on state:

TypeScript
interface UsersState {
  list: User[];
  current: User | null;
  loading: boolean;
}

export const useUsersStore = defineStore("users", {
  state: (): UsersState => ({
    list: [],
    current: null,
    loading: false,
  }),
});

The interface version is longer but reads like documentation, and you can export UsersState to use elsewhere. Use as for one or two awkward properties and an interface when the state is large.

flowchart TD
    A["state() returns..."] --> B{"Is the initial value<br/>specific enough?"}
    B -->|"0, 'text', true"| C["Inferred. Nothing to add."]
    B -->|"[], null, {}"| D["Add 'as Type' to the property"]
    B -->|"Many such fields"| E["Write an interface<br/>and annotate state()"]

Add types only where the initial value is too vague.

Typing getters

Getters that use only state are inferred. A getter that uses this (to reach another getter) needs an explicit return type, because TypeScript cannot work out a circular reference:

TypeScript
getters: {
  doubled: (state) => state.count * 2,
  // uses this, so annotate the return type:
  quadrupled(): number {
    return this.doubled * 2;
  },
},

If you forget the annotation you get an error like "implicitly has return type 'any' because it does not have a return type annotation". Add : number (or whatever it returns) and it goes away. The getters lesson covers this in detail.

Typing actions

Actions are ordinary methods. Type their parameters and return values as you would any function:

TypeScript
actions: {
  async load(id: number): Promise<void> {
    this.loading = true;
    try {
      const res = await fetch(`/api/users/${id}`);
      this.current = (await res.json()) as User;
    } finally {
      this.loading = false;
    }
  },
},

Inside an action, this is typed as the whole store, so this.current has the type User | null.

Reading types from the store

You sometimes need the type of a store, for example in a function parameter:

TypeScript
type UsersStore = ReturnType<typeof useUsersStore>;

function describe(store: UsersStore): string {
  return store.current?.name ?? "nobody";
}

For only the state, use UsersStore["$state"]. To get the storeToRefs result type, let inference do it: const { current } = storeToRefs(store) is a Ref<User | null>.

Runnable demo: the shapes in JavaScript

The next demo uses the same users store without types. The empty list and the null current user are exactly the awkward cases from above, and the code handles them in the way the types would force you to.

A users store with null and an empty list

Press "Select unknown id": find returns undefined, the ?? null turns it into null, and the getter prints "nobody". In TypeScript, User | null makes the compiler remind you to handle that case.

Typing a state that is a union

Sometimes the shape depends on a status. A discriminated union keeps impossible states out:

TypeScript
type RequestState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "error"; message: string }
  | { status: "done"; data: User[] };

export const useRequestStore = defineStore("request", {
  state: () => ({ request: { status: "idle" } as RequestState }),
});

Now store.request.data only exists after checking store.request.status === "done". It costs a few lines and removes a whole class of bugs ("loading is true and there is also an error").

Tips

  • Prefer null over undefined for "no value yet": it survives JSON serialization and is easier to test.
  • Keep type definitions next to the store or in a types.ts file the store imports.
  • Do not use any for state. It switches off checking in every component that reads the store.
  • Pinia ships its own types; you do not install @types/pinia.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does TypeScript infer for list: [] in state()?

    An empty array literal has no element information, so you must add a cast such as [] as User[].
  2. 2. When must a getter have an explicit return type?

    A getter that refers to the store through this creates a circular inference, so TypeScript needs the annotation.
  3. 3. Which option documents the whole state shape and can be exported?

    An interface annotated on state() names the shape in one place and can be reused elsewhere.
  4. 4. How do you get the type of a store?

    useUsersStore is a function; its return value is the store, so ReturnType gives the store type.

Summary

  • Pinia infers state, getter and action types from your definitions.
  • Add as Type for [], null and {}, or annotate state() with an interface.
  • Getters that use this need an explicit return type.
  • ReturnType<typeof useXStore> gives the store type.
  • Discriminated unions model request status without impossible combinations.

Next: Organizing Stores