Skip to main content
To write code in LangGraph, you need a good understanding of Python’s type hinting system. Because LangGraph passes a shared State around, we must precisely annotate what kinds of data are allowed inside our State.

1. Dictionaries vs. TypedDicts

Regular Dictionary πŸ“–

A standard Python dictionary allows any keys and values without enforcing any rules.
  • Pros: Flexible and fast.
  • Cons: No type safety. The code does not check if key names are spelled correctly or if values are of the correct type, leading to potential runtime crashes.

Typed Dictionary ⌨

A TypedDict allows us to define a dictionary with a fixed set of keys and specific types for each key. This is the primary way we define Graph States in LangGraph.
  • Pros: Explicit, self-documenting, and validated by static analysis tools (like Ruff or Pyright) to catch bugs early.

2. Union Type 🀝

A Union indicates that a variable can hold one of several specified types.
πŸ’‘ Note: In Python 3.10+, you can write int | float instead of Union[int, float].

3. Optional Type πŸ€”

An Optional type specifies that a variable can either be of a specific type, or None. It is shorthand for Union[Type, None].

4. Any Type 🎲

Any is a special type that matches any and all types. It turns off type checking for that variable.
  • Use Any sparingly, as it bypasses the safety benefits of type checking.

5. Lambda Functions ⏳

A lambda function is a small, anonymous function defined in a single line using the lambda keyword. In LangGraph, we often use lambdas as simple passthrough nodes or quick routers.