Typescript 如何定义与特定类型对象匹配的接口?

Typescript 如何定义与特定类型对象匹配的接口?,typescript,Typescript,在一段代码中,我想做一种元编程,我想定义一个函数,我可以将某些类型作为参数传递给它(因此不是类型的实例,而是类型本身) 我想将接受的类型限制为某个类或其子类 我试图通过以下代码实现这一点: class ABase {} class AConc extends ABase {} class B {} interface IAClass { new(): ABase; } function meta(AT: IAClass) { console.log('foo'); } // Th

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

我想将接受的类型限制为某个类或其子类

我试图通过以下代码实现这一点:

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)
给了我一个编译器错误,这是理所当然的。另一方面,尽管传入的类型不是从
ABase
派生的,但最后3个调用编译时没有任何错误

我做错了什么?有没有办法做到这一点?

您想要,但typescript还不支持

Typescript团队建议在类中使用
\u brand
字段:

class ABase {private __brand: ABase}