Prompt
Always validate data existence and type before accessing properties or methods to prevent runtime errors from null/undefined values. This includes:
- Array bounds checking before indexing
- Object property existence verification
- Type validation before method calls
- 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:
- Use optional chaining (?.) for nested object access
- Provide default values using nullish coalescing (??)
- Add explicit null checks for critical operations
- Validate array indices before access
- Check object type and property existence before destructuring
This prevents the most common causes of runtime errors and improves code reliability.