首页 > 解决方案 > 基于另一种类型的子集的类型,其键以特定字符串开头

问题描述

我正在尝试从另一种类型创建一个类型。该类型将包含基于其前缀的键子集。

基本类型示例:

interface Foo {
  axisControl: FormControl;
  directionControl: FormControl;

  filteredAxis: Observable<string[]>;
  filteredDirection: Observable<string[]>;
}

type Bar = // I want to write something only based on the prefix "filtered"

预期结果:

{
  filteredAxis: Observable<string[]>;
  filteredDirection: Observable<string[]>;
}

这可能吗?怎么做?

到目前为止我已经尝试过:

Pick<Foo, `filtered${string}`>

但这会引发错误。

标签: typescript

解决方案


您需要通过交集缩小选择的类型:

type FooWithFiltered = Pick<Foo, `filtered${string}` & keyof Foo>

操场


推荐阅读