G6 provides comprehensive TypeScript definitions for type-safe graph development. The type system covers configuration options, data structures, style properties, event interfaces, and extension APIs with full IntelliSense support.
// Essential type imports for G6 development
import type {
// Core interfaces
Graph,
GraphOptions,
GraphData,
// Element data types
NodeData,
EdgeData,
ComboData,
ElementDatum,
// Style interfaces
NodeStyle,
EdgeStyle,
ComboStyle,
// Configuration types
LayoutOptions,
BehaviorOptions,
PluginOptions,
TransformOptions,
// Event interfaces
IElementEvent,
IPointerEvent,
IKeyboardEvent,
IDragEvent,
IViewportEvent,
// Utility types
ID,
State,
Point,
Size,
Padding,
ElementType,
Placement
} from '@antv/g6';// Core identifier and primitive types
type ID = string | number; // Element identifier
type State = string; // Element state name
type Point = [number, number]; // 2D coordinate
type Vector2 = [number, number]; // 2D vector
type Vector3 = [number, number, number]; // 3D vector
// Size specifications
type Size =
| number // Uniform size
| [number] // Uniform size (array form)
| [number, number] // Width and height
| [number, number, number]; // Width, height, and depth
// Padding specifications
type Padding =
| number // Uniform padding
| [number] // Uniform padding
| [number, number] // Vertical and horizontal
| [number, number, number, number]; // Top, right, bottom, left
// Element type enumeration
type ElementType = 'node' | 'edge' | 'combo';
// Direction specifications
type EdgeDirection = 'in' | 'out' | 'both';
type HierarchyKey = 'combo' | 'tree';
// Placement options for UI components
type Placement =
| 'top' | 'top-left' | 'top-right'
| 'bottom' | 'bottom-left' | 'bottom-right'
| 'left' | 'left-top' | 'left-bottom'
| 'right' | 'right-top' | 'right-bottom'
| 'center';// Axis-aligned bounding box
interface AABB {
x: number; // Left coordinate
y: number; // Top coordinate
width: number; // Box width
height: number; // Box height
}
// Transform matrix (for viewport transforms)
interface Transform {
x: number; // Translation X
y: number; // Translation Y
k: number; // Scale factor
r?: number; // Rotation angle (optional)
}
// Color specifications
type Color = string; // CSS color string
type ColorArray = [number, number, number]; // RGB array
type ColorWithAlpha = [number, number, number, number]; // RGBA arrayinterface GraphData {
nodes?: NodeData[]; // Node definitions
edges?: EdgeData[]; // Edge definitions
combos?: ComboData[]; // Combo definitions
}
// Partial data for updates
interface PartialGraphData {
nodes?: PartialNodeLikeData<NodeData>[];
edges?: PartialEdgeData<EdgeData>[];
combos?: PartialNodeLikeData<ComboData>[];
}
// Required data (with defaults applied)
interface RequiredGraphData {
nodes: NodeData[];
edges: EdgeData[];
combos: ComboData[];
}// Node data structure
interface NodeData {
id: ID; // Unique identifier
type?: string; // Node type (defaults to graph config)
data?: Record<string, unknown>; // Custom data properties
style?: NodeStyle; // Style property overrides
states?: State[]; // Applied states
combo?: ID | null; // Parent combo ID
children?: ID[]; // Child node IDs (tree mode)
}
// Edge data structure
interface EdgeData {
id?: ID; // Optional unique identifier
source: ID; // Source node ID
target: ID; // Target node ID
type?: string; // Edge type (defaults to graph config)
data?: Record<string, unknown>; // Custom data properties
style?: EdgeStyle; // Style property overrides
states?: State[]; // Applied states
}
// Combo data structure
interface ComboData {
id: ID; // Unique identifier
type?: string; // Combo type (defaults to graph config)
data?: Record<string, unknown>; // Custom data properties
style?: ComboStyle; // Style property overrides
states?: State[]; // Applied states
combo?: ID | null; // Parent combo ID (nested combos)
children?: ID[]; // Child element IDs
}
// Union types for element data
type ElementDatum = NodeData | EdgeData | ComboData;
type NodeLikeData = NodeData | ComboData;// Common style properties for all elements
interface BaseStyleProps {
// Visibility and positioning
visibility?: 'visible' | 'hidden';
zIndex?: number;
// Fill and stroke
fill?: string;
fillOpacity?: number;
stroke?: string;
strokeOpacity?: number;
lineWidth?: number;
lineDash?: number[];
lineDashOffset?: number;
// General appearance
opacity?: number;
cursor?: string;
// Transform
transform?: string;
transformOrigin?: string;
// Filter effects
filter?: string;
// Animation
transition?: string;
}interface NodeStyle extends BaseStyleProps {
// Position and size
x?: number; // X coordinate
y?: number; // Y coordinate
z?: number; // Z coordinate (3D mode)
size?: Size; // Node size
// Node-specific styling
radius?: number; // Border radius (for rect nodes)
// Collapse/expand (tree nodes)
collapsed?: boolean; // Whether node is collapsed
collapsedSize?: Size; // Size when collapsed
collapsedMarker?: boolean; // Show collapse indicator
// Sub-component styles (using Prefix utility type)
// Label properties
labelText?: string | ((data: NodeData) => string);
labelFill?: string;
labelFontSize?: number;
labelFontFamily?: string;
labelFontWeight?: string | number;
labelPosition?: 'top' | 'bottom' | 'left' | 'right' | 'center';
labelOffsetX?: number;
labelOffsetY?: number;
labelMaxWidth?: number;
labelWordWrap?: boolean;
labelWordWrapWidth?: number;
labelBackground?: boolean;
labelBackgroundFill?: string;
labelBackgroundStroke?: string;
labelBackgroundRadius?: number;
labelBackgroundPadding?: Padding;
// Icon properties
iconText?: string; // Icon font character
iconSrc?: string; // Image source URL
iconFill?: string;
iconFontSize?: number;
iconFontFamily?: string;
iconWidth?: number;
iconHeight?: number;
iconOffsetX?: number;
iconOffsetY?: number;
// Badge properties
badgeText?: string | number;
badgeFill?: string;
badgeTextFill?: string;
badgeFontSize?: number;
badgeFontFamily?: string;
badgeRadius?: number;
badgeOffsetX?: number;
badgeOffsetY?: number;
badgePadding?: Padding;
// Halo properties (selection outline)
halo?: boolean;
haloFill?: string;
haloStroke?: string;
haloStrokeWidth?: number;
haloStrokeOpacity?: number;
haloRadius?: number;
// Port properties (connection points)
port?: boolean;
portFill?: string;
portStroke?: string;
portRadius?: number;
// Tree-specific properties
childrenNode?: ID[]; // Child node instances
childrenData?: NodeData[]; // Child node data
}interface EdgeStyle extends BaseStyleProps {
// Edge path properties
curvature?: number; // Curve intensity (for curved edges)
controlPoints?: Point[]; // Bezier control points
// Arrow properties
startArrow?: boolean; // Show start arrow
endArrow?: boolean; // Show end arrow
startArrowType?: 'triangle' | 'circle' | 'diamond' | 'vee' | 'path';
endArrowType?: 'triangle' | 'circle' | 'diamond' | 'vee' | 'path';
startArrowSize?: number; // Start arrow size
endArrowSize?: number; // End arrow size
startArrowOffset?: number; // Start arrow offset from node
endArrowOffset?: number; // End arrow offset from node
startArrowFill?: string; // Start arrow fill color
endArrowFill?: string; // End arrow fill color
// Loop edge properties (self-loops)
loop?: boolean; // Enable loop mode
loopClockwise?: boolean; // Loop direction
loopDist?: number; // Loop distance from node
// Label properties
label?: boolean; // Show label
labelText?: string | ((data: EdgeData) => string);
labelFill?: string;
labelFontSize?: number;
labelFontFamily?: string;
labelPosition?: 'start' | 'middle' | 'end' | number; // Position (0-1 for custom)
labelAutoRotate?: boolean; // Rotate label with edge
labelOffsetX?: number;
labelOffsetY?: number;
labelBackground?: boolean;
labelBackgroundFill?: string;
labelBackgroundStroke?: string;
labelBackgroundRadius?: number;
labelBackgroundPadding?: Padding;
// Badge properties
badge?: boolean;
badgeText?: string | number;
badgeFill?: string;
badgeTextFill?: string;
badgeFontSize?: number;
badgePosition?: 'start' | 'middle' | 'end';
badgeOffsetX?: number;
badgeOffsetY?: number;
// Halo properties
halo?: boolean;
haloStroke?: string;
haloStrokeWidth?: number;
haloStrokeOpacity?: number;
}interface ComboStyle extends NodeStyle {
// Combo-specific properties
padding?: Padding; // Internal padding when expanded
collapsedSize?: Size; // Size when collapsed
collapsedFill?: string; // Fill color when collapsed
collapsedStroke?: string; // Stroke color when collapsed
// Collapsed marker (expand/collapse indicator)
collapsedMarker?: boolean; // Show collapsed indicator
collapsedMarkerFill?: string;
collapsedMarkerStroke?: string;
collapsedMarkerSize?: number;
collapsedMarkerOffsetX?: number;
collapsedMarkerOffsetY?: number;
// Child management
childrenNode?: ID[]; // Child element instances
childrenData?: NodeLikeData[]; // Child element data
}interface GraphOptions extends CanvasOptions, ViewportOptions {
// Data configuration
data?: GraphData; // Initial data
// Element type configurations
node?: NodeOptions; // Default node configuration
edge?: EdgeOptions; // Default edge configuration
combo?: ComboOptions; // Default combo configuration
// Layout configuration
layout?: LayoutOptions; // Layout algorithm settings
// Interaction configuration
behaviors?: BehaviorOptions; // Interactive behaviors
plugins?: PluginOptions; // UI plugins
transforms?: TransformOptions; // Data transforms
// Appearance configuration
theme?: ThemeOptions; // Visual theme
animation?: boolean | AnimationEffectTiming; // Animation settings
}
// Element type configuration interfaces
interface NodeOptions {
type?: string; // Default node type
style?: NodeStyle; // Default node style
state?: Record<State, Partial<NodeStyle>>; // State-specific styles
palette?: string[] | Record<string, string>; // Color palette for categories
}
interface EdgeOptions {
type?: string; // Default edge type
style?: EdgeStyle; // Default edge style
state?: Record<State, Partial<EdgeStyle>>; // State-specific styles
palette?: string[] | Record<string, string>; // Color palette for categories
}
interface ComboOptions {
type?: string; // Default combo type
style?: ComboStyle; // Default combo style
state?: Record<State, Partial<ComboStyle>>; // State-specific styles
}interface CanvasOptions {
// Container configuration
container: HTMLElement | string; // DOM container
width?: number; // Canvas width
height?: number; // Canvas height
// Rendering configuration
renderer?: 'canvas' | 'svg' | 'webgl'; // Rendering engine
devicePixelRatio?: number; // Device pixel ratio
background?: string; // Background color
// Performance options
enableOptimize?: boolean; // Enable performance optimizations
optimizeThreshold?: number; // Optimization threshold
}
interface ViewportOptions {
// Initial viewport state
zoom?: number; // Initial zoom level
zoomRange?: [number, number]; // Min and max zoom
// Viewport behavior
autoFit?: 'view' | 'center' | false; // Auto-fit behavior
padding?: Padding; // Viewport padding
// Transform constraints
translateExtent?: [[number, number], [number, number]]; // Pan boundaries
}// Base event interface
interface IEvent {
type: string; // Event type name
target?: any; // Event target
originalEvent?: Event; // Original DOM event
preventDefault?: () => void; // Prevent default behavior
stopPropagation?: () => void; // Stop event bubbling
}
// Element interaction events
interface IElementEvent extends IEvent {
target: Element; // Target element
targetType: ElementType; // Element type
client: Point; // Client coordinates
canvas: Point; // Canvas coordinates
viewport: Point; // Viewport coordinates
originalEvent: MouseEvent; // Original mouse event
}
// Pointer events (mouse/touch)
interface IPointerEvent extends IEvent {
client: Point; // Client coordinates
canvas: Point; // Canvas coordinates
viewport: Point; // Viewport coordinates
originalEvent: MouseEvent | TouchEvent; // Original pointer event
}
// Drag events
interface IDragEvent extends IElementEvent {
movement: Point; // Movement delta [dx, dy]
cumulative: Point; // Total movement [totalDx, totalDy]
originalEvent: MouseEvent | TouchEvent;
}
// Keyboard events
interface IKeyboardEvent extends IEvent {
key: string; // Key pressed
code: string; // Key code
ctrlKey: boolean; // Control key state
shiftKey: boolean; // Shift key state
altKey: boolean; // Alt key state
metaKey: boolean; // Meta key state
originalEvent: KeyboardEvent; // Original keyboard event
}
// Wheel/scroll events
interface IWheelEvent extends IPointerEvent {
deltaX: number; // Horizontal scroll
deltaY: number; // Vertical scroll
deltaZ: number; // Z-axis scroll
deltaMode: number; // Delta mode
originalEvent: WheelEvent; // Original wheel event
}
// Viewport transform events
interface IViewportEvent extends IEvent {
transform: Transform; // Current transform state
}interface LayoutOptions {
type: string; // Layout algorithm type
animation?: boolean | AnimationConfig; // Animation configuration
onLayoutStart?: () => void; // Start callback
onLayoutEnd?: () => void; // End callback
onTick?: (progress: number) => void; // Progress callback
[key: string]: any; // Algorithm-specific options
}
// Animation configuration
interface AnimationConfig {
duration?: number; // Animation duration (ms)
easing?: string | ((t: number) => number); // Easing function
delay?: number; // Animation delay (ms)
fill?: 'none' | 'forwards' | 'backwards' | 'both'; // Fill mode
}interface BehaviorOptions {
key?: string; // Unique behavior identifier
type: string; // Behavior type name
enable?: boolean | ((event: any) => boolean); // Enable condition
[key: string]: any; // Behavior-specific options
}
interface UpdateBehaviorOption {
key: string; // Behavior key to update
[key: string]: any; // Options to update
}
// Shortcut key specification
type ShortcutKey = string | string[]; // Key or key combinationinterface PluginOptions {
key?: string; // Unique plugin identifier
type: string; // Plugin type name
[key: string]: any; // Plugin-specific options
}
interface UpdatePluginOption {
key: string; // Plugin key to update
[key: string]: any; // Options to update
}// Prefix utility type for sub-component styles
type Prefix<K extends string, T> = {
[P in keyof T as `${K}${Capitalize<string & P>}`]?: T[P];
};
// Partial data types for updates
type PartialNodeLikeData<T> = {
id: ID;
type?: string;
data?: Partial<T['data']>;
style?: Partial<T['style']>;
states?: State[];
[key: string]: any;
};
type PartialEdgeData<T> = {
source?: ID;
target?: ID;
id?: ID;
type?: string;
data?: Partial<T['data']>;
style?: Partial<T['style']>;
states?: State[];
};
// Function type for data accessors
type DataAccessor<T, R = any> = (data: T, index: number) => R;
// Conditional types for method overloads
type DataReturnType<T extends ID | ID[]> =
T extends ID[] ? ElementDatum[] :
T extends ID ? ElementDatum | undefined :
ElementDatum[];interface ThemeOptions {
// Color schemes
primary?: string; // Primary color
secondary?: string; // Secondary color
background?: string; // Background color
surface?: string; // Surface color
// Element defaults
node?: Partial<NodeStyle>; // Default node styles
edge?: Partial<EdgeStyle>; // Default edge styles
combo?: Partial<ComboStyle>; // Default combo styles
// State styles
hover?: Record<ElementType, Partial<any>>; // Hover state styles
selected?: Record<ElementType, Partial<any>>; // Selected state styles
active?: Record<ElementType, Partial<any>>; // Active state styles
}
// Style property extraction utilities
type StyleKeys<T> = {
[K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];
type StyleProps<T> = Pick<T, StyleKeys<T>>;// Type guard implementations
const isNodeData = (data: ElementDatum): data is NodeData => {
return 'id' in data && !('source' in data || 'target' in data);
};
const isEdgeData = (data: ElementDatum): data is EdgeData => {
return 'source' in data && 'target' in data;
};
const isComboData = (data: ElementDatum): data is ComboData => {
return 'id' in data && !('source' in data || 'target' in data) && 'children' in data;
};
// Usage with type narrowing
const processElementData = (data: ElementDatum) => {
if (isNodeData(data)) {
// TypeScript knows data is NodeData here
console.log('Node:', data.id);
} else if (isEdgeData(data)) {
// TypeScript knows data is EdgeData here
console.log('Edge:', data.source, '->', data.target);
} else if (isComboData(data)) {
// TypeScript knows data is ComboData here
console.log('Combo:', data.id, 'with', data.children?.length, 'children');
}
};// Generic interfaces with constraints
interface ExtensionConstructor<T extends BaseExtension = BaseExtension> {
new (options: any): T;
defaultOptions?: any;
}
interface DataTransformer<TInput = any, TOutput = any> {
transform(data: TInput): TOutput;
validate?(data: TInput): boolean;
}
// Extension registration with type safety
const register = <T extends BaseExtension>(
category: ExtensionCategory,
type: string,
constructor: ExtensionConstructor<T>
): void => {
// Registration implementation
};