如何定义匹配某些类型对象的接口?

时间:2018-01-14 19:14:19

标签: typescript

在一段代码中,我想做一种元编程,我想定义一个函数,我可以将某些类型作为参数传递给它(所以不是一种类型,但类型本身)。

我想将接受的类型限制为某个类或其后代。

我尝试使用以下代码实现此目的:

class ABase {}
class AConc extends ABase {}

class B {}

interface IAClass {
  new(): ABase;
}

function meta(AT: IAClass) {
  console.log('foo');
}

// This gives an error, as it should.
meta(5);

// These compile, this is the usage I want.
meta(ABase);
meta(AConc);

// These compile, but this is what I don't want to allow.
// I only want to be able to pass in types deriving from ABase.
meta(B);
meta(Array);
meta(Number);

第一次调用meta(5)给了我一个编译错误,理所当然。另一方面,最后3次调用编译没有任何错误,尽管传入的类型不是从ABase派生的。

我做错了什么?有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:2)

您想要nominal typing,但打字稿不支持。

Typescript团队建议在您的课程中使用__brand字段:

class ABase {private __brand: ABase}
相关问题