打字稿:类型ConstructorParameters不接受泛型

时间:2019-12-20 21:49:36

标签: typescript types

使用打字稿3.7,我有一个接口,该接口的属性旨在接受构造函数:

interface IConstruct<T> {
  type: new (...args:ConstructorParameters<T>) => T;
}

我认为IConstruct<User>将具有属性{type: User}
但是编译器告诉我T不能在那儿使用。为什么会这样?

  

TS2344:类型T不满足约束'new(... args:any)=>任何'

1 个答案:

答案 0 :(得分:2)

ConstructorParameters的类型如下:

type ConstructorParameters<T extends new (...args: any) => any> =
  T extends new (...args: infer P) => any ? P : never;

因此类型参数T本身必须扩展约束extends new (...args: any) => any定义的某种构造函数。像上面这样写上面的例子,你应该很好:

class User {
    constructor(public name: string) { }
}

// add constructor function type constraint for T
interface IConstruct<T extends new (...args: any) => any> {
    // we can use built-in InstanceType to infer instance type from class type
    type: new (...args: ConstructorParameters<T>) => InstanceType<T>;
}

type UserConstruct = IConstruct<typeof User>

const constr: UserConstruct = {
    type: User
}

constr.type // new (name: string) => User

const userInstance = new constr.type("John") // userInstance: User

console.log(userInstance.name) // John

Playground