Typescript - 仅选择以目标字符串开头的属性键

sim*_*994 3 typescript typescript-typings

我想从另一个类型创建一个新类型,用于Pick包含指定的属性。我发现了这个:Typescript:以目标字符串开头时排除属性键

我需要相反的。

起源:

type Origin = {
  testA: string,
  testB: string,
  _c: string,
  _d: string,
  example: string,
  anotherName: string,
}
Run Code Online (Sandbox Code Playgroud)

结果我会:

type Result = {
  _c: string,
  _d: string
};

Run Code Online (Sandbox Code Playgroud)

我尝试过

type Result = Pick<Origin, `_${string}`>
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Type '`_${string}`' does not satisfy the constraint 'keyof Origin'
Run Code Online (Sandbox Code Playgroud)

Nul*_*ble 8

你不能使用Pick,因为第二个参数必须是keyof T,所以你不能只是

type Result = Pick<Origin, `_${string}`>
Run Code Online (Sandbox Code Playgroud)

处理此问题的一种正确方法如下:

type PickStartsWith<T extends object, S extends string> = {
    [K in keyof T as K extends `${S}${infer R}` ? K : never]: T[K]
}
Run Code Online (Sandbox Code Playgroud)

这会正确地仅选择以前缀开头的键:

const result: PickStartsWith<Origin, "_"> = {
    _c: "",
    _d: "",
    testA: "", // error
}
Run Code Online (Sandbox Code Playgroud)

这是游乐场链接