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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With