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

React-TypeScript条件类型组件:如何判断props类型并访问属性

解决React泛型组件中区分联合类型Props的方法

方法1:自定义类型守卫(Type Predicate)

编写自定义函数明确判断props的类型,TypeScript会基于这个判断自动缩小类型范围:

// 定义类型守卫函数
function isA(props: A | B): props is A {
  return 'a' in props;
}

function isB(props: A | B): props is B {
  return 'b' in props;
}

// 组件内部使用
function Component<T extends A | B>(props: T) {
  if (isA(props)) {
    // 此处props被推断为A类型,可安全访问props.a
    console.log(props.a);
  } else {
    // 此处props被推断为B类型,可安全访问props.b
    console.log(props.b);
  }
}

方法2:直接检查属性存在性

无需额外定义函数,直接用in操作符判断属性是否存在,TypeScript会自动完成类型缩小:

function Component<T extends A | B>(props: T) {
  if ('a' in props) {
    // props被推断为A类型
    return <div>{props.a}</div>;
  } else {
    // props被推断为B类型
    return <div>{props.b}</div>;
  }
}

方法3:使用区分联合类型(Discriminated Union)

如果可以修改A、B的类型定义,添加一个共同的区分字段(比如type),能让类型判断更清晰可靠:

// 修改类型定义,添加区分字段
type A = { type: 'a'; a: SomeCustomType };
type B = { type: 'b'; b: SomeOtherDifferentType };

// 组件内部通过区分字段判断
function Component<T extends A | B>(props: T) {
  switch (props.type) {
    case 'a':
      // props为A类型
      return <div>{props.a}</div>;
    case 'b':
      // props为B类型
      return <div>{props.b}</div>;
  }
}

补充说明

调用组件时无需手动指定类型,TypeScript会根据传入的props自动推断:

// 正确写法,无需手动标注类型
const MyComponentA = <Component a={"test"} />;
const MyComponentB = <Component b={1231241} />;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:10:20