这是我喜欢的类型:

type newType = { 
  a: string, 
  b: string,
  c: { 
    x: string,
    y: string,
    z: string,
  },
}

我怎么才能只挑c.y个呢?我希望我的输出是:

type newTypePick = { 
  c: { 
    y: string,
  },
}

我不想编写手动代码,比如:

type newTypePick = {
  c: Pick<newType['c'], 'y'>;
};

推荐答案

我是ts-essentials的维护者,我们有一个名为DeepPick的实用程序类型,它可以在您的场景中提供帮助.

I stress在这里,只有当你需要更通用的方法时(你需要在不同的地方至少做两次,层数可能不同),使用这种方法将是有益的,否则请忽略这一点,使用Pick和映射类型的方法

您可以使用此类型仅获取所需的值:

type newType = { 
  a: string, 
  b: string,
  c: { 
    x: string,
    y: string,
    z: string,
  },
}

type OnlyCY = DeepPick<
  // ^? { c: { y: string } }
  newType,
  {
    c: {
      y: never
    }
  }
>;

简化的解决方案将看起来简短而漂亮:

type Primitive = string | number | boolean | bigint | symbol | undefined | null;

type Builtin = Primitive | Function | Date | Error | RegExp;

type AnyRecord = Record<string, any>;

export type DeepPick<Type, Filter> = Type extends Builtin
  ? Type
  : Filter extends AnyRecord
  ? {
      // iterate over keys of Type, which keeps the information about keys: optional, required or readonly
      [Key in keyof Type as Key extends keyof Filter ? Key : never]: Filter[Key & keyof Filter] extends true
        ? Type[Key]
        : Key extends keyof Filter
        ? DeepPick<Type[Key], Filter[Key]>
        : never;
    }
  : never;

如果你有任何问题,请告诉我

Typescript相关问答推荐

根据另一个成员推断类成员的类型

动态判断TypScript对象是否具有不带自定义类型保护的键

typescribe警告,explate—deps,useEffect依赖项列表

返回同时具有固定键和变量键的对象的函数的返回类型

如何正确地对类型脚本泛型进行限制

如何使用Zod使一个基于其他字段值的字段为必填字段?

类型脚本基于数组作为泛型参数展开类型

尽管对象的类型已声明,但未解析的变量<;变量

防止重复使用 Select 器重新渲染

Angular 自定义验证控件未获得表单值

vue-tsc失败,错误引用项目可能无法禁用vue项目上的emit

专用路由组件不能从挂钩推断类型

如何避免从引用<;字符串&>到引用<;字符串|未定义&>;的不安全赋值?

17个Angular 的延迟观察.如何在模板中转义@符号?

在Thunk中间件中输入额外参数时Redux工具包的打字脚本错误

TypeScrip:使用Cypress测试包含插槽的Vue3组件

T的typeof键的Typescript定义

为什么过滤器不改变可能的类型?

在类型{}上找不到带有string类型参数的索引签名 - TypeScript

递归类型名称