这是我来这里寻求建议之前最后一次失败的尝试。我做错了什么吗?
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,而不是排除它们。您需要更改条件中的逻辑:希望这可以帮助。
如果你调整
ExcludeNullableFields
到这个..基本上我正在检查是否可以从任何类型中提取 null 。如果类型不包含
null
,则 extract 将返回never
。但如果 Extract 确实找到了该类型,null
那么我就知道该字段可以为空。