这是我来这里寻求建议之前最后一次失败的尝试。我做错了什么吗?
interface Something {
id: string;
name: string | null;
}
interface AnotherThing {
id: string;
name: string;
}
type ExcludeNullableFields<A> = {
[K in keyof A as A[K] extends string | null ? K : never]: A[K] ;
};
type NamelessThing = ExcludeNullableFields<Something>;
// desired outcome: { id: string }
type NamedThing = ExcludeNullableFields<AnotherThing>;
// desired outcome: { id: string; name: string }
您的
ExcludeNullableFields
条件类型当前包含 string | 类型的字段null,而不是排除它们。您需要更改条件中的逻辑:
type ExcludeNullableFields<A> = {
[K in keyof A as A[K] extends string ? K : never]: A[K];
};
type NamelessThing = ExcludeNullableFields<Something>;
// result: { id: string }
type NamedThing = ExcludeNullableFields<AnotherThing>;
// result: { id: string; name: string }
希望这有帮助。