我希望编写一个递归省略字段的类型工具。你可以像这样命名和使用它:OmitRecursively<SomeType, 'keyToOmit'>
我尝试使用映射类型+条件类型来实现,但是当所有必需字段都被正确地输入类型(因此从嵌套类型中消失)时,我卡在了可选字段被忽略的情况。
// This is for one function that removes recursively __typename field
// that Appolo client adds
type Deapolify<T extends { __typename: string }> = Omit<
{ [P in keyof T]: T[P] extends { __typename: string } ? Deapolify<T[P]> : T[P] },
'__typename'
>
// Or more generic attempt
type OmitRecursively<T extends any, K extends keyof T> = Omit<
{ [P in keyof T]: T[P] extends any ? Omit<T[P], K> : never },
K
>
期望的行为是忽略根和所有嵌套键,这些键具有应该被递归省略的键类型。例如:
type A = {
keyToKeep: string
keyToOmit: string
nested: {
keyToKeep: string
keyToOmit: string
}
nestedOptional?: {
keyToKeep: string
keyToOmit: string
}
}
type Result = OmitRecursively<A, 'keyToOmit'>
type Expected = {
keyToKeep: string
nested: {
keyToKeep: string
}
nestedOptional?: {
keyToKeep: string
}
}
Expected === Result