在 TypeScript 中,如何创建一个映射的条件类型来删除字符串类型的属性 |空

问题描述 投票:0回答:1

这是我来这里寻求建议之前最后一次失败的尝试。我做错了什么吗?

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 }
typescript mapped-types conditional-types
1个回答
0
投票

您的

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 }

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.