Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript deep omit with dot notation

As template literal types are now supported in TypeScript, is it possible to have something like the following?

interface Data {
  a: number;
  b: {
    c: number;
    d: number;
  }
}

type OmitDeep<T, K> = ...

type WithoutC = OmitDeep<Data, 'b.c'>

Where WithoutC will be inferred as:

interface WithoutC {
  a: number;
  b: {
   d: number
  }
}
like image 518
Deftomat Avatar asked May 13 '26 22:05

Deftomat


1 Answers

You can use this type to map dotted path to an array path:

type UnDot<T extends string> =
    T extends `${infer A}.${infer B}` ? [A, B] : ''

type ProperyArray = UnDot<'a.b'>; // ["a", "b"]

And then use this answer to remove nested properties:

Types for deleting object at specific nested path

Edit for any number of nesting levels:

type UnDot<T extends string> =
    T extends `${infer A}.${infer B}`
    ? [A, ...UnDot<B>]
    : [T];
like image 179
Roberto Zvjerković Avatar answered May 16 '26 18:05

Roberto Zvjerković