Typescript 从对象动态创建类型
假设我有以下两种类型:Typescript 从对象动态创建类型,typescript,dynamic-typing,conditional-types,Typescript,Dynamic Typing,Conditional Types,假设我有以下两种类型: export type CollectionNames = 'twitter:tweets' | 'twitter:users' | 'twitter:metadata-cashtag' export type CollectionType<T extends CollectionNames> = T extends 'twitter:tweets' ? Tweet : T extends 'twitter:users' ? User :
export type CollectionNames = 'twitter:tweets' | 'twitter:users' | 'twitter:metadata-cashtag'
export type CollectionType<T extends CollectionNames> =
T extends 'twitter:tweets' ? Tweet :
T extends 'twitter:users' ? User :
T extends 'twitter:metadata-cashtag' ? CashtagMetadataDb :
never
其思想是,多个模块将拥有自己的CollectionType
类型,然后在导入根模块中将其聚合为一个CollectionType
。因此,如果我使用*as
导入两个模块Coin
和Twitter
,它看起来像这样:
type CollectionName = Twitter.CollectionNames | Coin.CollectionNames
type CollectionType<T extends CollectionName> =
T extends Twitter.CollectionNames ? Twitter.CollectionType<T> :
T extends Coin.CollectionNames ? Coin.CollectionType<T> :
never
export interface Collections {
'twitter:tweets': Tweet,
'twitter:users': User,
'twitter:metadata-cashtag': CashtagMetadataDb
}
我认为在这种情况下,您根本不需要条件类型;你可以用它来代替。您可能可以创建一个像
typings
这样的对象,并从中派生一个类型,但除非您在运行时需要该对象(并且有Tweet
、User
等类型的对象),否则我认为您应该创建这样的接口类型:
type CollectionName = Twitter.CollectionNames | Coin.CollectionNames
type CollectionType<T extends CollectionName> =
T extends Twitter.CollectionNames ? Twitter.CollectionType<T> :
T extends Coin.CollectionNames ? Coin.CollectionType<T> :
never
export interface Collections {
'twitter:tweets': Tweet,
'twitter:users': User,
'twitter:metadata-cashtag': CashtagMetadataDb
}
然后,您的CollectionNames
和CollectionType
类型可以根据该类型定义:
export type CollectionNames = keyof Collections;
export type CollectionType<K extends CollectionNames> = Collections[K];
希望有帮助。祝你好运 我认为在这种情况下,您根本不需要条件类型;你可以用它来代替。您可能可以创建一个像
typings
这样的对象,并从中派生一个类型,但除非您在运行时需要该对象(并且有Tweet
、User
等类型的对象),否则我认为您应该创建这样的接口类型:
type CollectionName = Twitter.CollectionNames | Coin.CollectionNames
type CollectionType<T extends CollectionName> =
T extends Twitter.CollectionNames ? Twitter.CollectionType<T> :
T extends Coin.CollectionNames ? Coin.CollectionType<T> :
never
export interface Collections {
'twitter:tweets': Tweet,
'twitter:users': User,
'twitter:metadata-cashtag': CashtagMetadataDb
}
然后,您的CollectionNames
和CollectionType
类型可以根据该类型定义:
export type CollectionNames = keyof Collections;
export type CollectionType<K extends CollectionNames> = Collections[K];
希望有帮助。祝你好运 您可以发布一个示例,说明如何使用
CollectionType
吗?使用edit更新问题扫描您可以发布一个示例,说明如何使用CollectionType
吗?使用edit更新问题这太棒了,完全符合我的需要!谢谢你的时间:)这太棒了,完全符合我的需要!感谢您抽出时间:)