根据条件创建子集联合类型。打字稿

Create subset union type, based on condition. TypeScript

我有以下 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 中可以吗?我该怎么做?

如果你认为只依赖于你需要什么,你应该能够使用接口来满足你的需要。

interface HierarchicalWidget {
    children: Widget[];
}

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

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