0Pricing
TypeScript Academy · Lesson

Derived State and Selectors with Types

Write typed selector functions for computed state.

Derived State and Selectors with Types is a free TypeScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Derived State?

Derived state is state computed from other state — like filtering a list or summing values. Selectors encapsulate this computation and can be memoized for performance.

// Raw state
const users: User[] = [/* ... */];
// Derived state: active users only
const activeUsers = users.filter(u => u.isActive);

Typed Selector Functions

Write selector functions with explicit return types to document what they compute and prevent type drift.

import type { RootState } from "./store";

const selectActiveUsers = (state: RootState): User[] =>
  state.users.filter((u) => u.isActive);

const selectUserCount = (state: RootState): number =>
  state.users.length;

reselect: Memoized Selectors

The reselect library (used by RTK) creates memoized selectors that only recompute when their inputs change.

import { createSelector } from "reselect";

const selectActiveUsers = createSelector(
  (state: RootState) => state.users,
  (users) => users.filter((u) => u.isActive)
);
// Return type inferred: User[]

Typed Parameterized Selectors

Factory selectors accept arguments and return a selector — useful for per-entity lookups.

const selectUserById = (id: string) =>
  createSelector(
    (state: RootState) => state.users,
    (users) => users.find((u) => u.id === id) ?? null
  );

// Usage: const user = useAppSelector(selectUserById("123"));

Zustand Selectors

In Zustand, pass a typed selector to the store hook to read only the needed slice.

const activeUsers = useUserStore((s) => s.users.filter(u => u.isActive));
// Inferred type: User[]

Derived State in React with useMemo

For local derived state, use useMemo with proper type annotations to memoize computed values in components.

const sortedUsers = useMemo(
  (): User[] => [...users].sort((a, b) => a.name.localeCompare(b.name)),
  [users]
);

Composing Selectors

Build complex selectors by composing simpler ones — reselect handles memoization across the chain.

const selectActiveUserNames = createSelector(
  selectActiveUsers,
  (users) => users.map((u) => u.name)
); // string[]

Type-Safe Zustand with immer for Derived Updates

When computing derived updates, use immer to mutate a draft state — TypeScript ensures only valid properties are touched.

const useStore = create<AppStore>()(immer((set) => ({
  users: [],
  activeCount: 0,
  setUsers: (users) =>
    set((draft) => {
      draft.users = users;
      draft.activeCount = users.filter((u) => u.isActive).length;
    }),
})));

Selector Return Type Inference

TypeScript infers return types from selectors, but explicit annotations improve readability and prevent accidental any from dynamic expressions.

// Inferred — may widen to any for complex expressions
const selectTotals = createSelector(
  (s: RootState) => s.cart.items,
  (items) => items.reduce((sum, i) => sum + i.price, 0) // inferred: number
);

Testing Selectors

Selectors are pure functions — test them by passing mock state and asserting the output type and value.

test("selectActiveUsers", () => {
  const state = { users: [{ id: "1", isActive: true }, { id: "2", isActive: false }] } as RootState;
  expect(selectActiveUsers(state)).toHaveLength(1);
});

Recap: Typed Selectors

Typed selectors: write functions taking RootState with explicit return types, use createSelector for memoization, compose selectors for complex derivations, and test them as pure functions.

Quick Check

What advantage does createSelector provide over a plain selector function?

What You Learned

Typed selectors take RootState and return precisely typed derived values. Use createSelector for memoization, compose selectors for complex logic, and write factory selectors for parameterized entity lookups.

Frequently asked questions

Is the “Derived State and Selectors with Types” lesson free?

Yes — the full text of “Derived State and Selectors with Types” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Derived State and Selectors with Types”?

Write typed selector functions for computed state. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Derived State and Selectors with Types” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Typing Redux Toolkit Slices and Thunks
  2. Zustand Store Typing Patterns
  3. XState: Typed State Machines
  4. Derived State and Selectors with Types
← Back to TypeScript Academy