Back to all reviewers

Use definite assignment assertions

cloudflare/agents
Based on 3 comments
TypeScript

When you're certain a value will be initialized but TypeScript can't infer this, use the definite assignment assertion operator (`!`) instead of `as any` or suppressing type errors. This maintains type safety while avoiding unnecessary null checks throughout your codebase.

Null Handling TypeScript

Reviewer Prompt

When you’re certain a value will be initialized but TypeScript can’t infer this, use the definite assignment assertion operator (!) instead of as any or suppressing type errors. This maintains type safety while avoiding unnecessary null checks throughout your codebase.

Avoid this pattern:

// Creates unnecessary undefined checks everywhere
#agent: Agent<Env, State> | undefined;

// Or suppressing valid type concerns
// @ts-expect-error TODO: fix this type error
await this._drainStream(response.body);

// Or forcing types unsafely  
}) as any

Instead, use definite assignment assertions when you know the value will be there:

// Tells TypeScript "trust us, it'll always be there"
#agent: Agent<Env, State>!;

Or add proper null checks when the value might actually be null:

// When the value could legitimately be null/undefined
if (response.body) {
  const reader = response.body.getReader();
  // ... handle the stream
}

This approach maintains TypeScript’s null safety benefits while eliminating false positives that lead to code pollution or unsafe type assertions.

3
Comments Analyzed
TypeScript
Primary Language
Null Handling
Category

Source Discussions