Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript mapped type with filtered keys

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 }.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading