【问题标题】:Allow a variable to have multiple types in ReactJS在 ReactJS 中允许变量具有多种类型
【发布时间】:2020-06-24 13:46:07
【问题描述】:

我已经定义了两种类型,比如 -

type A = $ReadOnly<{
  a: ?$ReadOnlyArray<string>,
  b: ?string,
}>;

type B = $ReadOnly<{
  c: ?$ReadOnlyArray<boolean>,
  d: ?number,
}>;

我想定义一个功能组件,它采用这两种类型中的任何一种,例如

type Input = {
  eitherType: type can be A or B
};

function abcd({eitherType}: Input): React.Node {
    // blah blah blah  
    // typecast to the particular type here
}

我不想使用any 来定义类型,有没有其他方法可以让这个变量同时具有这两种类型?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

使用union 创建可以是以下两种类型之一的类型:

type Input = {
  eitherType: A | B
};

【讨论】:

  • 这使得转换为特定类型变得困难。
  • 是的,您的示例中的类型很难让机器分开。通常需要联合的对象类型有一个共同的值,比如字符串type,可以与discriminate the union进行比较。
  • 或调用 Object.prototype.hasOwnProperty 来检查是否存在 abcd 就足以区分类型,因为这些键中的每一个都完全存在联合中的一种类型。
【解决方案2】:

其中一种解决方案是在这里实现多态

创建 A 类 创建B类并从A类继承 然后使用 Class Type 作为输入类型。 在调用函数时声明 A 类对象并分配 B 的实例 希望它会工作

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多