You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中TypeScript联合类型属性访问报错问题求助

How to Fix TypeScript Error When Accessing src on a Union Type ImageType[] | ImageType

Hey there! I totally get why you're hitting this TypeScript error—let's break down what's happening and how to fix it.

The Root of the Problem

Your value prop is a union type: ImageType[] | ImageType. When you check typeof value === 'object', TypeScript can't tell if you're dealing with a single ImageType object or an array (since arrays are also considered objects in JavaScript). That's why accessing value.src throws an error—TS isn't sure it's safe.

Solutions to Fix the Error

1. Use Array.isArray() to Rule Out Arrays First

This is the simplest and most straightforward fix. By checking if value is not an array, TypeScript will automatically narrow the type to ImageType:

// Inside your component logic
if (!Array.isArray(value)) {
  // TypeScript now knows value is definitely ImageType
  console.log(value.src);
} else {
  // Handle the array case here
  value.forEach(image => console.log(image.src));
}

2. Create a Custom Type Guard for Strict Validation

If you want more control (or need to validate the structure of ImageType), you can write a type guard function. This tells TypeScript exactly what makes a value an ImageType:

// Define the type guard
function isSingleImage(item: ImageType[] | ImageType): item is ImageType {
  return !Array.isArray(item) && 'src' in item && 'alt' in item;
}

// Use it in your component
if (isSingleImage(value)) {
  // TS confirms value is ImageType here
  console.log(value.src);
}

3. Leverage the multiple Prop to Narrow Types

Since your component has a multiple prop, you can use it to hint to TypeScript what value should be. When multiple is false, value should be a single ImageType:

if (!multiple) {
  // We can safely assert the type here because of the multiple prop's logic
  const singleImage = value as ImageType;
  console.log(singleImage.src);
} else {
  // When multiple is true, value is an array
  (value as ImageType[]).forEach(image => console.log(image.src));
}

Note: Only use type assertions like as ImageType if you're confident the logic holds (i.e., multiple: false always pairs with a single ImageType value).

Quick Note About null

If there's any chance value could be null (your current Props define it as required, so maybe not), make sure to add a null check:

if (!Array.isArray(value) && value !== null) {
  console.log(value.src);
}

内容的提问来源于stack exchange,提问作者mirik999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:27:28