Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Exclude Property key when starts with target string

Tags:

typescript

I want to make new object type from Original type should be filtered when property key starts with the Target String.

Origin type:

type Origin = {
    a: string,
    b: string,
    _c: string,
    _d: string,
}

Result type as I want.:

// type Result = SomethingWork<Origin, '_'>;
type Result = {
    a: string,
    b: string
};

Origin type has dynamic property keys. so It's not correct, if using type as direct like '_c' | '_d'

like image 570
styliss Avatar asked Mar 03 '26 17:03

styliss


1 Answers

This is now possible with template literal types

type FilterNotStartingWith<Set, Needle extends string> = Set extends `${Needle}${infer _X}` ? never : Set

Example:

type Origin = {
  a: string,
  b: string,
  _c: string,
  _d: string,
}

type FilteredKeys = FilterNotStartingWith<keyof Origin, '_'>
type NewOrigin = Pick<Origin, FilteredKeys>
/*
type NewOrigin = {
  a: string;
  b: string;
}
*/
like image 135
Joonas Avatar answered Mar 06 '26 08:03

Joonas