Typescript mapped type with filtered keys

53 Views Asked by At

If I have a type like:

type T = {
  a: string,
  _a: string,
  b: number,
  _c: boolean,
  /* ... any number of unknown properties ... */
};

Is there anyway I can define a new mapped type which has all (and only) properties of T which do not begin with the letter _?

For instance I want to resolve the above type to { a: string, b: number }.

1

There are 1 best solutions below

3
jcalz On BEST ANSWER

Yes, you can just use the Omit<T, K> utility type where the omitted key type is the pattern template literal type `_${string}`:

type FilteredT = Omit<T, `_${string}`>;
/* type FilteredT = {
    a: string;
    b: number;
} */

Pattern template literal types were implemented in microsoft/TypeScript#40598 (but I don't see any handbook or release notes documentation for it). The type `_${string}` can be read as "the underscore character followed by any string"; i.e., "any string that starts with an underscore".

Playground link to code