在下面(和附加的)示例中,我试图使用类型为
DeepKeyOf<T>
的泛型来传递嵌套类型遗漏。就其本身而言,DeepKeyOf<T>
按预期工作,只有当我尝试传递扩展 DeepKeyOf<T>
的泛型时它才不起作用。
下面,我有
MyInterface<TEntity extends IBaseEntity, TOmissions extends DeepKeyOf<TEntity>>
,它试图接受 TOmissions
并将它们传递给 DeepOmittedEntity
。据我所知,我错过了什么?
// https://medium.com/xgeeks/typescript-utility-keyof-nested-object-fa3e457ef2b2
type DeepKeyOf<T> = {
[Key in keyof T & (string | number)]: T[Key] extends object ? `${Key}` | `${Key}.${DeepKeyOf<T[Key]>}` : `${Key}`
}[keyof T & (string | number)];
// DeepOmit works as expected - https://stackoverflow.com/a/75823617/3329760
type DeepOmit<T, K extends PropertyKey> = {
[P in keyof T as P extends K ? never : P]: DeepOmit<T[P], K extends `${Exclude<P, symbol>}.${infer R}` ? R : never>
}
// Combining DeepKeyOf and DeepOmit works perfectly!
type DeepOmittedEntity<TEntity extends IBaseEntity, TOmissions extends DeepKeyOf<TEntity>> = DeepOmit<TEntity, "id" | TOmissions>;
interface IBaseEntity {
id: string;
more: string;
other: string;
}
// This works as expected
const someObject: DeepOmittedEntity<IBaseEntity, "more"> = {
other: "this works"
}
// The add method does not like TOmissions - see linked example
interface MyInterface<TEntity extends IBaseEntity, TOmissions extends DeepKeyOf<TEntity>> {
add(entities: DeepOmittedEntity<TEntity, TOmissions>[]): void;
}
编辑1:
如果我将
DeepKeyOf<T>
替换为 string
,一切正常,但由于显而易见的原因,智能感知不起作用。