Skip to content

Commit 7ff34e8

Browse files
committed
fix type narrowing issue
1 parent 5a7c1be commit 7ff34e8

File tree

1 file changed

+29
-15
lines changed

1 file changed

+29
-15
lines changed

src/components/imageLightbox/index.tsx

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,27 @@ const isExternalImage = (src: string): boolean => src.startsWith('http');
2525
const getImageUrl = (src: string, imgPath: string): string =>
2626
isExternalImage(src) ? src : imgPath;
2727

28-
const hasValidDimensions = (width?: number, height?: number): width is number =>
29-
width != null &&
30-
height != null &&
31-
!isNaN(width) &&
32-
!isNaN(height) &&
33-
width > 0 &&
34-
height > 0;
28+
type ValidDimensions = {
29+
height: number;
30+
width: number;
31+
};
32+
33+
const getValidDimensions = (
34+
width?: number,
35+
height?: number
36+
): ValidDimensions | null => {
37+
if (
38+
width != null &&
39+
height != null &&
40+
!isNaN(width) &&
41+
!isNaN(height) &&
42+
width > 0 &&
43+
height > 0
44+
) {
45+
return {width, height};
46+
}
47+
return null;
48+
};
3549

3650
export function ImageLightbox({
3751
src,
@@ -48,7 +62,7 @@ export function ImageLightbox({
4862
// Check if we should use Next.js Image or regular img
4963
// Use Next.js Image for internal images with valid dimensions
5064
// Use regular img for external images or when dimensions are invalid/missing
51-
const shouldUseNextImage = !isExternalImage(src) && hasValidDimensions(width, height);
65+
const validDimensions = !isExternalImage(src) ? getValidDimensions(width, height) : null;
5266

5367
const handleClick = (e: React.MouseEvent) => {
5468
// If Ctrl/Cmd+click, open image in new tab
@@ -88,13 +102,13 @@ export function ImageLightbox({
88102

89103
// Render the appropriate image component
90104
const renderImage = () => {
91-
if (shouldUseNextImage) {
92-
// Type assertion is safe here because hasValidDimensions guarantees these are valid numbers
105+
if (validDimensions) {
106+
// TypeScript knows validDimensions.width and validDimensions.height are both numbers
93107
return (
94108
<Image
95109
src={src}
96-
width={width as number}
97-
height={height as number}
110+
width={validDimensions.width}
111+
height={validDimensions.height}
98112
style={{
99113
width: '100%',
100114
height: 'auto',
@@ -148,12 +162,12 @@ export function ImageLightbox({
148162

149163
{/* Image container */}
150164
<div className="relative flex items-center justify-center">
151-
{shouldUseNextImage ? (
165+
{validDimensions ? (
152166
<Image
153167
src={src}
154168
alt={alt}
155-
width={width as number}
156-
height={height as number}
169+
width={validDimensions.width}
170+
height={validDimensions.height}
157171
className="max-h-[90vh] max-w-[90vw] object-contain"
158172
style={{
159173
width: 'auto',

0 commit comments

Comments
 (0)