在使用Typescript实施期间立即检查类的静态方面

时间:2019-05-06 07:20:54

标签: typescript interface

我处于以下情况,具有两个通用的Queue接口:一个用于实现接口的类的实例端,另一个用于静态端:

export interface Queue<T> {
  // instances stuff
}

export interface QueueConstructor<T> {
  new(arrayOfT?: Array<T>): Queue<T>;
  // static stuff
}

我想直接在实现阶段检查实现是否正确实现了静态方面。我不想使用提出的第一种解决方法in the documentation,而第二种方法由于泛型而显得不可用。

也许可以使用装饰器来做到这一点,但我无法找到合适的解决方案。

1 个答案:

答案 0 :(得分:3)

泛型可与执行检查方法的函数一起使用,理想情况下,您应使用泛型来保留在新类上声明的任何其他成员:

export interface Queue<T> {
  push(item: T): Queue<T>;
}

export interface QueueConstructor<T> {
  new(arrayOfT?: Array<T>): Queue<T>;

}

function checkQueue<T extends QueueConstructor<any>>(cls: T): T{
  return cls;
}

const myQueue = checkQueue(class <T> {
  constructor(public arrayOfT?: Array<T>) {

  }
  push(item: T): Queue<T>{
    return this;
  }
})

new myQueue<number>();

const myBadQueue = checkQueue(class <T> { // err
  constructor(length: number) {

  }
  push(item: T): Queue<T>{
    return this;
  }
})

这个完全相同的功能也可以用作装饰器,它将标记相同的问题

function checkQueue<T extends QueueConstructor<any>>(cls: T): T{
    return cls;
}

@checkQueue
class myQueue<T> {
    constructor(public arrayOfT?: Array<T>) {

    }
    push(item: T): Queue<T>{
    return this;
    }
}

new myQueue<number>();

@checkQueue // err
class myBadQueue<T> { 
    constructor(length: number) {

    }
    push(item: T): Queue<T>{
    return this;
    }
}