Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Pick only properties key that starts with a target string

I would like to create a new type from another one, using Pick to include specified properties. I've found this: Typescript: Exclude Property key when starts with target string

I need the opposite.

Origin:

type Origin = {
  testA: string,
  testB: string,
  _c: string,
  _d: string,
  example: string,
  anotherName: string,
}

Result I would:

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

I've tried with

type Result = Pick<Origin, `_${string}`>

but I got the following error:

Type '`_${string}`' does not satisfy the constraint 'keyof Origin'
like image 671
simone_s1994 Avatar asked Oct 19 '25 08:10

simone_s1994


1 Answers

You can't use Pick because the second parameter must be keyof T, so you can't just

type Result = Pick<Origin, `_${string}`>

One correct way to handle this is the following:

type PickStartsWith<T extends object, S extends string> = {
    [K in keyof T as K extends `${S}${infer R}` ? K : never]: T[K]
}

This correctly picks only the keys that starts with a prefix:

const result: PickStartsWith<Origin, "_"> = {
    _c: "",
    _d: "",
    testA: "", // error
}

Here a playground link

like image 81
Nullndr Avatar answered Oct 21 '25 03:10

Nullndr