我是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;
如果你有任何问题,请告诉我