Code without type hints is like an API without documentation. Nobody knows:
- What does the function expect? - Which data type should be passed?
- What does it return? - String? Array? Object? Null?
- When are there errors? - Only at runtime, when it's too late
function get_post_excerpt( $post ) {
if ( $post ) {
return substr( $post->post_content, 0, 100 );
}
return null;
}Problems:
$postcould be anything - int, string, WP_Post, null?- Return value is unclear - string or null?
- IDE can't help - no autocompletion
- Errors only visible at runtime
- Other developers have to read code to understand usage
function get_post_excerpt( WP_Post $post ): string {
return substr( $post->post_content, 0, 100 );
}Benefits:
- Clear: Expects a
WP_Postobject - Clear: Always returns a
string - IDE shows errors immediately (before running!)
- Autocompletion works perfectly
- Self-documenting code
// BAD: What happens if no post is found?
function get_post_title( $id ) {
$post = get_post( $id );
return $post->post_title;
}
// GOOD: Explicitly states that null is possible
function get_post_title( int $id ): ?string {
$post = get_post( $id );
return $post ? $post->post_title : null;
}// BAD: No idea what $post should be
class PostProcessor {
private $post;
}
// GOOD: Crystal clear
class PostProcessor {
private WP_Post $post;
}// GOOD: Function accepts ID or slug
function get_post_by_id_or_slug( int|string $identifier ): ?WP_Post {
// ...
}✅ Always use type hints (parameters + return)
✅ ?Type for nullable values
✅ Property type hints in classes
✅ DocBlocks for arrays of objects (@return WP_Post[])
✅ Union types when multiple types make sense
❌ Don't skip type hints - "Because it's faster"
❌ Don't fall back to mixed when you can be more specific
❌ DocBlocks are not a replacement for real type hints
With type hints you get:
- ✨ Autocompletion
⚠️ Immediate error indication- 🔍 "Go to definition" works
- 🔄 Safe refactorings