我正在寻求为特定类制作Parameters
的通用打字稿。
type Example<T> = Parameters<UserRepository[T]>[0]
但是我收到此错误:
类型'T'不能用于索引类型“ UserRepository”
也尝试过:
type Example<T extends string> = Parameters<UserRepository[T]>[0]
我目前有这个:
type Params = Parameters<UserRepository["members"]>[0] &
Parameters<UserRepository["contacts"]>[0] &
Parameters<UserRepository["user"]>[0]
我想创建两个泛型ClassMethod
和ClassMethods
。
type ClassMethod<C, M> = string
type Param = ClassMethod<UserRepository, 'members'>
或
type ClassMethod<T> = Parameters<UserRepository[T]>[0]
type Param = ClassMethod<'members'> // where the generic has `UserRepository `in it.
和
type ClassMethods<C, M> = string
type Params = ClassMethods<UserRepository, ['members', 'contacts', 'user']>
答案 0 :(得分:0)
ClassMethod<'meow'>
第一个示例很简单,该类被嵌入d
type ClassMethod<T extends keyof UserRepository> = Parameters<UserRepository[T]>[0]
ClassMethod<UserRepository, 'meow'>
type ClassMethod<c extends any, T extends keyof c> = Parameters<c[T]>[0]
ClassMethods<UserRepository, 'meow' | 'woof'>
class UserRepository {
meow (i: { catSound: string }) {
}
woof (i: { dogSound: string }) {
}
}
// As usual, see https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
type ClassMethods<C, M extends keyof C> = UnionToIntersection<{
[K in M]: C[K] extends ((...args: any[]) => any) ? Parameters<C[K]>[0] : never
}[M]>
type Parms = ClassMethods<UserRepository, 'meow' | 'woof'>
// Or if you really want an array...
type ClassMethods2<C, M extends Array<keyof C>> = UnionToIntersection<{
[K in M[number]]: C[K] extends ((...args: any[]) => any) ? Parameters<C[K]>[0] : never
}[M[number]]>
type Parms2 = ClassMethods2<UserRepository, ['meow', 'woof']>
特别感谢typescript gitter上的Gerrit Birkeland
。