【发布时间】:2020-08-26 16:05:18
【问题描述】:
我想创建一个泛型类型,该类型将保存一个存在于具有该方法参数的 clas 上的方法,但是当我将类实例提供给泛型时,我得到 [never, never]。
我会在一个类中使用这种类型,所以我提供了一个潜在用法的简化示例
类中的示例用法
type AnyClass = { new (...arg0: any): any }
type SingeTask<V extends InstanceType<AnyClass>> = [
Extract<keyof V, (...arg0: any) => any>,
Parameters<Extract<keyof V, (...arg0: any) => any>>
]
type Task<V extends InstanceType<AnyClass>> = {
task: SingeTask<V>
resolve: (value?: unknown) => void
reject: (reason: any) => void
}
class Queue<T extends AnyClass> {
instances: InstanceType<T>[] = []
queue: Task<T>[] = []
object: T
constructor(object: T) {
this.object = object
}
addInstance( number:number) {
for (i; i < number; i++) {
this.instances.push(new this.object())
}
runTasksInQueue(
instance: InstanceType<T>,
{ task, reject, resolve }: Task<T>
) {
try {
const respone = Reflect.apply(instance, ...task)
resolve(respone)
} catch (error) {
reject(error)
} finally {
const task = this.queue.pop()
if (task) {
this.runTasksInQueue(instance, task)
} else {
this.instances.push(instance)
}
}
}
addTaskToQueue(task: SingeTask<T>) {
return new Promise((resolve, reject) => {
const instance = this.instances.pop()
if (instance) {
this.runTasksInQueue(instance, { task, resolve, reject })
} else {
this.queue.push({ task, resolve, reject })
}
})
}
}
队列类的使用
class mockClass {
sth?: number
constructor(n?: number) {
this.sth = n
}
getNumber(n: number) {
return n
}
}
const instanceQueue = new queue(mockClass)
instanceQueue.addInstance(5)
instanceQueue.addTaskToQueue() // Here I get error [never,never] but I would expect to be able to pass [getNumber,(number e.g - 10)] and receive 10
【问题讨论】:
标签: typescript typescript-typings typescript-generics