typescript 类型声明中的收缩类型

gmxoilav  于 2023-02-14  发布在  TypeScript
关注(0)|答案(1)|浏览(158)

对于下面的示例,我尝试在类型声明期间区分基类型

type Schedule = {
  flag_active : boolean,
}
type Channel = {
  flag_archived : boolean
}

type CreateChangeLog = {
  from : null,
  to : Schedule | Channel
}
type DeleteChangeLog = {
  from : Schedule | Channel,
  to : null
}

type AllChanges = CreateChangeLog | DeleteChangeLog

如果type AllChanges的定义无法更改,那么如何检索Schedule类型呢?

4sup72z8

4sup72z81#

如果您有一个像ScheduleOrChannel这样的联合类型,计算如下:

type AllChanges = CreateChangeLog | DeleteChangeLog

type ScheduleOrChannel = NonNullable<AllChanges["from"]>;
// type ScheduleOrChannel = Schedule | Channel

并且您希望过滤它以仅包含那些与某个超类型匹配的联合成员,则可以使用Extract<T, U>实用程序类型,如下所示:

type JustSchedule = Extract<ScheduleOrChannel, { flag_active: any }>
// type JustSchedule = Schedule

type JustChannel = Extract<ScheduleOrChannel, { flag_archived: any }>
// type JustChannel = Channel

Extract<T, U>只是一个分布式条件类型,它被实现为

type Extract<T, U> = T extends U ? T : never

因此,您始终可以编写自己的自定义联合过滤操作,该操作使用其他标准来保留/拒绝成员,例如HasKey实用程序类型:

type HasKey<T, K extends PropertyKey> =
    T extends unknown ? K extends keyof T ? T : never : never;

type JustSchedule1 = HasKey<ScheduleOrChannel, "flag_active">
// type JustSchedule1 = Schedule

type JustChannel2 = HasKey<ScheduleOrChannel, "flag_archived">
// type JustChannel2 = Channel

Playground代码链接

相关问题