【问题标题】:Create subset union type, based on condition. TypeScript根据条件创建子集联合类型。打字稿
【发布时间】:2018-02-09 19:53:58
【问题描述】:

我有以下Widget 类型:

enum WidgetType {
  Page = "Page",
  Tab = "Tab",
  Value = "Value",
  Chart = "Chart"
}
type PageWidget = {
  type: WidgetType.Page;
  children: Widget[];
};
type TabWidget = {
  type: WidgetType.Tab;
  children: Widget[];
};
type ValueWidget = {
  type: WidgetType.Value;
};
type ChartWidget = {
  type: WidgetType.Chart;
};
type Widget = PageWidget | TabWidget | ValueWidget | ChartWidget;

基于此,我想创建新类型调用WidgetWithChildren,它必须是具有children 属性的小部件的联合(在这种情况下是PageWidgetTabWidget 的联合),但我想要让它动态化,所以当有一个新类型的 Widget 时,它会自动出现在 WidgetWithChildren 中。

我想要类似的东西:

type WidgetWithChildren = Pick<Widget, "take widgets children">;

在 TypeScript 中可以吗?我该怎么做?

【问题讨论】:

    标签: typescript union-types


    【解决方案1】:

    如果您认为只取决于您需要什么,那么您应该能够使用界面来满足您的需求。

    interface HierarchicalWidget {
        children: Widget[];
    }
    
    // Example usage
    function needsChildren(widget: HierarchicalWidget) {
        for (const child of widget.children) {
            console.log(child.type);
        }
    }
    

    任何具有children 类型Widget[] 的对象都可以满足此接口,无论它是否显式实现它。这允许您的代码依赖于HierarchicalWidget 的概念,而无需了解具体的实现,例如PageWidgetTabWidget

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2019-08-27
      • 2020-10-01
      • 2021-07-08
      • 2022-01-13
      • 2023-03-28
      • 2023-02-13
      相关资源
      最近更新 更多