给定一个判别式,得到被判别联合的相应成员的 属性 类型

Given a discriminant, get type of a property for corresponding member of discriminated union

我有以下判别联​​合,其中 属性 id 根据判别式的值获取不同的类型:

type TableKind = 'administration' | 'data'

type AdministrationTableId = 'Modules' | 'Users' | 'Roles'
type DataTableId = number

type GenericIdentifier<K extends TableKind, ID> = { kind: K, id: ID }

type AdministrationTableIdentifier = GenericIdentifier<'administration', AdministrationTableId>
type DataTableIdentifier = GenericIdentifier<'data', DataTableId>

type TableIdentifier = AdministrationTableIdentifier | DataTableIdentifier

我想制作一个通用类型,它采用判别式和 returns 相应联合成员的 id 属性 的类型:

type GetTableIdType<K extends TableKind> = ???

type AdminId = GetTableIdType<'administration'> // returns AdministrationTableID
type DataId = GetTableIdType<'data'> // returns DataTableId

这可能吗?这是如何实现的?

只需使用Extract

type TableKind = 'administration' | 'data'

type AdministrationTableId = 'Modules' | 'Users' | 'Roles'
type DataTableId = number

type GenericIdentifier<K extends TableKind, ID> = { kind: K, id: ID }

type AdministrationTableIdentifier = GenericIdentifier<'administration', AdministrationTableId>

type DataTableIdentifier = GenericIdentifier<'data', DataTableId>

type TableIdentifier = AdministrationTableIdentifier | DataTableIdentifier


type GetTableIdType<K extends TableKind> = Extract<TableIdentifier, { kind: K }>['id']

type AdminId = GetTableIdType<'administration'> // returns AdministrationTableID
type DataId = GetTableIdType<'data'> // returns DataTableId

Playground