带点符号的 Typescript 深度省略

Def*_*mat 2 typescript template-literals

由于 TypeScript 现在支持模板文字类型,是否可以有类似以下内容?

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

type OmitDeep<T, K> = ...

type WithoutC = OmitDeep<Data, 'b.c'>
Run Code Online (Sandbox Code Playgroud)

其中WithoutC将被推断为:

interface WithoutC {
  a: number;
  b: {
   d: number
  }
}
Run Code Online (Sandbox Code Playgroud)

rit*_*taj 5

您可以使用此类型将点路径映射到数组路径:

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

type ProperyArray = UnDot<'a.b'>; // ["a", "b"]
Run Code Online (Sandbox Code Playgroud)

然后使用这个答案来删除嵌套属性:

用于删除特定嵌套路径处的对象的类型

编辑任意数量的嵌套级别:

type UnDot<T extends string> =
    T extends `${infer A}.${infer B}`
    ? [A, ...UnDot<B>]
    : [T];
Run Code Online (Sandbox Code Playgroud)