Always validate data existence and type before accessing properties or methods to prevent runtime errors from null/undefined values. This includes:

  1. Array bounds checking before indexing
  2. Object property existence verification
  3. Type validation before method calls
  4. Use of optional chaining and nullish coalescing operators

Example of unsafe code:

function toolCallStateToSystemToolCall(state: ToolCallState): string {
  return state.toolCall.function.name;  // Unsafe - multiple potential null points
}

Safe version:

function toolCallStateToSystemToolCall(state: ToolCallState): string {
  if (!state?.toolCall?.function) {
    throw new Error("Invalid tool call state");
  }
  return state.toolCall.function.name ?? "unknown";
}

Key practices:

This prevents the most common causes of runtime errors and improves code reliability.