如何使用函数输入类型“ typeof A”返回类型“ A”?

时间:2019-07-26 00:57:08

标签: typescript

我有这个沙箱示例

class A {
    doSomething() {}
}
class B {}

const collection = {
    a: new A(),
    b: new B()
}

const findInstance = <T>(list: any, nonInstance: T): T => {
    for (const item in list) {
    if (list[item] instanceof (nonInstance as any)) {
            return list[item] as any
        }
    }
    throw new Error('Unable to find thingo')
}

const a: A = findInstance(collection, A)

a.doSomething()

我得到的类型错误是

Property 'doSomething' is missing in type 'typeof A' but required in type 'A'.

我得到的是typeof A,我想要的是A

https://www.typescriptlang.org/play/#code/MYGwhgzhAECC0G8BQ1XQCYHsDKmC2ApgC4AWAlgHYDmAFAJSIC+SzokMAQk0ksJhRCLQ+IEAWBEy-aAF5EKNGABc0CgQDucegBoFqAEYq1mjvRY8+AoQDNK6AJJWwFYAVnQAPABUAfDRBkgirOAJ7aqvyOgs6uKl50cbI+8mjQ1pgATtA0loLQZEQEePkU0AGCDMipZNbZ5UQA2gVFALol0S4EmLU0FJFOndCQQxQhdJV6qVMZxACuGaX1TYV4bcOhk6nMW5OkGZiaxtAAohn7GTQA5ACqFGD6YtBEmGl2T+TUmJd05rz8eco4O5bBQHANXDlMKJxJJ+OFYD8kGAAHRYXCEUiUWh0IA

2 个答案:

答案 0 :(得分:4)

nonInstance类型声明从T更改为new(...args: any[]) => T

这是更新的功能签名:

const findInstance = <T>(list: any, nonInstance: new(...args: any[]) => T): T => {
    // ...
}

这表明您想要类型T的构造函数,而不是类型T本身的实例。

这是一个相关的问题:Using a generic type argument with `typeof T`

另一个例子是TypeScript手册:https://www.typescriptlang.org/docs/handbook/generics.html#using-class-types-in-generics

答案 1 :(得分:0)

您是要在此表达式中使用'new'吗?我想不是因为您调用了变量nonInstance ... A的类型是缺少doSomething方法的类本身(除非您会使用static关键字,但这也不是正确的解决方案)...因此我认为您需要包括new()=> T来告诉编译器您要与实例进行比较,

const findInstance = <T>(list: any, instance: new () => T): T => {
  for (const item in list) {
    if (list[item] instanceof (instance as any)) {
      return list[item] as any;
    }
  }
  throw new Error('Unable to find thingo');
};