Skip to content

Types

This reference documents TypeGraph’s TypeScript types and utility functions.

The full node type returned from store operations.

type Node<N extends NodeType> = Readonly<{
id: NodeId<N>; // Branded ID type
kind: N["kind"]; // Node kind name
meta: {
version: number; // Monotonic version counter
validFrom: string | undefined; // Temporal validity start (ISO string)
validTo: string | undefined; // Temporal validity end (ISO string)
createdAt: string; // Created timestamp (ISO string)
updatedAt: string; // Updated timestamp (ISO string)
deletedAt: string | undefined; // Soft delete timestamp (ISO string)
};
}> & z.infer<N["schema"]>; // Schema properties are flattened

Branded string type for type-safe node IDs. Prevents accidentally mixing IDs from different node types.

type NodeId<N extends NodeType> = string & { readonly [__nodeId]: N };

Example:

import { type NodeId } from "@nicia-ai/typegraph";
type PersonId = NodeId<typeof Person>;
type CompanyId = NodeId<typeof Company>;
function getPersonById(id: PersonId): Promise<Node<typeof Person>> {
// TypeScript prevents passing a CompanyId here
return store.nodes.Person.getById(id);
}

Extracts just the property types from a node definition. Use this when you only need the schema data without node metadata.

type NodeProps<N extends NodeType> = z.infer<N["schema"]>;

Example:

import { type NodeProps } from "@nicia-ai/typegraph";
type PersonProps = NodeProps<typeof Person>;
// { name: string; email?: string; age?: number }
// Useful for form data, API payloads, or validation
function validatePersonData(data: PersonProps): boolean {
return data.name.length > 0;
}

Type-safe reference to a node of a specific kind. Used for edge collection methods to enforce that endpoints match the allowed node types. Defaults to NodeType when no type parameter is given.

type NodeRef<N extends NodeType = NodeType> = Node<N> | Readonly<{ kind: N["kind"]; id: string }>;

Accepts either:

  • A Node<N> instance (e.g., the result of store.nodes.Person.create())
  • An explicit object with the correct type name and ID

The node type available in select() context. Properties are flattened (not nested under props).

type SelectableNode<N extends NodeType> = Readonly<{
id: string;
kind: N["kind"];
meta: {
version: number;
validFrom: string | undefined;
validTo: string | undefined;
createdAt: string;
updatedAt: string;
deletedAt: string | undefined;
};
}> & z.infer<N["schema"]>; // Properties are flattened

Example:

// In select context, access properties directly
.select((ctx) => ({
id: ctx.p.id, // string
name: ctx.p.name, // Direct property access (not ctx.p.props.name)
email: ctx.p.email,
created: ctx.p.meta.createdAt,
}))

The full edge type returned from store operations. The From and To type parameters carry compile-time node type information for the edge endpoints.

type Edge<
E extends EdgeType = EdgeType,
From extends NodeType = NodeType,
To extends NodeType = NodeType,
> = Readonly<{
id: EdgeId<E>; // Branded ID type
kind: E["kind"];
fromKind: From["kind"];
fromId: NodeId<From>;
toKind: To["kind"];
toId: NodeId<To>;
meta: {
validFrom: string | undefined; // Temporal validity start (ISO string)
validTo: string | undefined; // Temporal validity end (ISO string)
createdAt: string; // Created timestamp (ISO string)
updatedAt: string; // Updated timestamp (ISO string)
deletedAt: string | undefined; // Soft delete timestamp (ISO string)
};
}> & z.infer<E["schema"]>; // Schema properties are flattened

Branded string type for type-safe edge IDs. Prevents accidentally mixing IDs from different edge types.

type EdgeId<E extends AnyEdgeType = AnyEdgeType> = string & { readonly [__edgeId]: E };

Example:

import { type EdgeId } from "@nicia-ai/typegraph";
type WorksAtId = EdgeId<typeof worksAt>;
function getEdgeById(id: WorksAtId): Promise<Edge<typeof worksAt>> {
return store.edges.worksAt.getById(id);
}

Extracts just the property types from an edge definition.

type EdgeProps<E extends EdgeType> = z.infer<E["schema"]>;

Example:

import { type EdgeProps } from "@nicia-ai/typegraph";
type WorksAtProps = EdgeProps<typeof worksAt>;
// { role: string; startDate?: string }

The edge type available in select() context. Properties are flattened.

type SelectableEdge<E extends EdgeType> = Readonly<{
id: string;
kind: E["kind"];
fromId: string;
toId: string;
meta: {
validFrom: string | undefined;
validTo: string | undefined;
createdAt: string;
updatedAt: string;
deletedAt: string | undefined;
};
}> & z.infer<E["schema"]>; // Edge properties are flattened

Example:

// Access edge properties in select context
.select((ctx) => ({
role: ctx.e.role, // Direct edge property access
salary: ctx.e.salary,
edgeId: ctx.e.id,
startedAt: ctx.e.meta.createdAt,
}))

A type-safe edge collection with From/To types extracted from the edge registration. This is what store.edges.* returns.

type TypedEdgeCollection<R extends EdgeRegistration> = EdgeCollection<
R["type"],
R["from"][number], // Union of allowed 'from' node types
R["to"][number] // Union of allowed 'to' node types
>;

A node collection with widened generics for runtime string-keyed access via store.getNodeCollection(kind). Exposes the full NodeCollection API (create, getById, find, count, createFromRecord, etc.) but accepts Record<string, unknown> for schema-typed parameters since the concrete node type is not known at compile time.

ID parameters (getById, getByIds, update, delete, hardDelete, bulkDelete) accept plain string instead of branded NodeId<N>, since the dynamic path typically receives IDs from edge metadata, snapshots, or external input where the brand is not available.

import type { DynamicNodeCollection } from "@nicia-ai/typegraph";
// Derived from NodeCollection<NodeType, string> with branded ID parameters widened to string

An edge collection with widened generics for runtime string-keyed access via store.getEdgeCollection(kind). Exposes the full EdgeCollection API (create, getById, find, count, findFrom, findTo, etc.) with widened endpoint types.

ID parameters (getById, getByIds, update, delete, hardDelete, bulkDelete, bulkUpsertById) accept plain string instead of branded EdgeId<E>, since the dynamic path typically receives IDs from edge metadata, snapshots, or external input where the brand is not available.

import type { DynamicEdgeCollection } from "@nicia-ai/typegraph";
// Derived from EdgeCollection<AnyEdgeType, NodeType, NodeType> with branded ID parameters widened to string

These types are used with store.subgraph() for typed neighborhood extraction.

Discriminated union of all runtime node types in a graph. Each member carries its own kind literal, so switch (node.kind) narrows the type automatically.

import type { AnyNode } from "@nicia-ai/typegraph";
type MyNode = AnyNode<typeof graph>;
// = Node<typeof Person> | Node<typeof Company> | ...

Discriminated union of all runtime edge types in a graph.

import type { AnyEdge } from "@nicia-ai/typegraph";
type MyEdge = AnyEdge<typeof graph>;
// = Edge<typeof worksAt> | Edge<typeof knows> | ...

Narrows AnyNode<G> to a subset of node kinds. Useful when store.subgraph() is called with includeKinds.

import type { SubsetNode } from "@nicia-ai/typegraph";
type TaskOrAgent = SubsetNode<typeof graph, "Task" | "Agent">;
// = Node<typeof Task> | Node<typeof Agent>

Narrows AnyEdge<G> to a subset of edge kinds.

import type { SubsetEdge } from "@nicia-ai/typegraph";
type TraversedEdges = SubsetEdge<typeof graph, "has_task" | "runs_agent">;

Options for store.subgraph(). See the store reference for the full parameter table.

type SubgraphOptions<G, EK, NK> = Readonly<{
edges: readonly EK[];
maxDepth?: number;
includeKinds?: readonly NK[];
excludeRoot?: boolean;
direction?: "out" | "both";
cyclePolicy?: "prevent" | "allow";
}>;

The return type of store.subgraph(). Contains the root node, a node index, and forward/reverse adjacency maps for immediate traversal.

type SubgraphResult<G, NK, EK> = Readonly<{
root: SubgraphNodeResult<G, NK> | undefined;
nodes: ReadonlyMap<string, SubgraphNodeResult<G, NK>>;
adjacency: ReadonlyMap<string, ReadonlyMap<EK, readonly SubgraphEdgeResult<G, EK>[]>>;
reverseAdjacency: ReadonlyMap<string, ReadonlyMap<EK, readonly SubgraphEdgeResult<G, EK>[]>>;
}>;

Controls what happens to edges when a node is deleted.

type DeleteBehavior = "restrict" | "cascade" | "disconnect";
ValueDescription
"restrict"Prevent deletion if edges exist
"cascade"Delete connected edges
"disconnect"Remove edges without error

Controls how many edges of a type can connect from/to a node.

type Cardinality = "many" | "one" | "unique" | "oneActive";
ValueDescription
"many"No limit on edges
"one"At most one edge per source node
"unique"At most one edge per source-target pair
"oneActive"At most one active edge (validTo is undefined) per source node

Controls how ontology relationships affect queries.

type InferenceType =
| "subsumption" // Query for X includes subclass instances
| "hierarchy" // Enables broader/narrower traversal
| "substitution" // Can substitute equivalent types
| "constraint" // Validation rules
| "composition" // Part-whole navigation
| "association" // Discovery/recommendation
| "none"; // No automatic inference

Configuration for variable-length (recursive) traversals.

type VariableLengthSpec = Readonly<{
minDepth: number; // Minimum hops (default: 1)
maxDepth: number; // Maximum hops (-1 = unlimited)
cyclePolicy: "prevent" | "allow"; // Cycle handling mode
pathAlias?: string; // Column alias for projected path
depthAlias?: string; // Column alias for projected depth
}>;

Available set operations for combining queries.

type SetOperationType = "union" | "unionAll" | "intersect" | "except";

Options for cursor-based pagination.

type PaginateOptions = Readonly<{
first?: number; // Items to fetch (forward)
after?: string; // Cursor to start after (forward)
last?: number; // Items to fetch (backward)
before?: string; // Cursor to start before (backward)
}>;

Result of a paginated query.

type PaginatedResult<R> = Readonly<{
data: readonly R[];
nextCursor: string | undefined;
prevCursor: string | undefined;
hasNextPage: boolean;
hasPrevPage: boolean;
}>;

Options for streaming results.

type StreamOptions = Readonly<{
batchSize?: number; // Items per batch (default: 1000)
}>;

Generates a unique ID using nanoid.

import { generateId } from "@nicia-ai/typegraph";
function generateId(): string;
const id = generateId(); // "V1StGXR8_Z5jdHi6B-myT"

Maximum depth for unbounded recursive traversals (10).

import { MAX_RECURSIVE_DEPTH } from "@nicia-ai/typegraph";
// MAX_RECURSIVE_DEPTH = 10

Recursive traversals are capped at this depth when no maxHops is specified in the recursive() options object. Explicit maxHops values are validated against MAX_EXPLICIT_RECURSIVE_DEPTH (1000). Cycle prevention is enabled by default. To allow revisits for maximum performance, use cyclePolicy: "allow".

Maximum allowed value for the maxHops option in recursive traversals (1000).

import { MAX_EXPLICIT_RECURSIVE_DEPTH } from "@nicia-ai/typegraph";
// MAX_EXPLICIT_RECURSIVE_DEPTH = 1000