繁体   English   中英

Typescript:从 function 的返回中定义 class 类型(并将其用作类型)

[英]Typescript: define a class type from the return of a function (and use it as a type)

有没有办法从 function 的返回中定义 class,然后将其用作接口中的属性类型?

class Foo {};
function makeFoo<T extends Foo>(classType: T): T {
  return classType;
}
const Foo2 = makeFoo(Foo);
new Foo(); // OK
new Foo2(); // OK
interface IFoo {
  foo1: Foo; // OK
  foo2: Foo2; // 'Foo2' refers to a value, but is being used as a type here.
}

真实世界的用例是我有一个 function ,它使用类的泛型类型向类添加了一些 static 方法。 所以,

class DataModel {}
class Foo<T extends DataModel> {}
class Bar extends Foo<DataModel> {
  getInstance() {
    return 'I am an instance';
  }
}

function addStatics<T extends DataModel, TF extends Foo<T>>(
  classType: TF,
): TF & { getStatic: () => T } {
  return Object.defineProperty(classType, 'getStatic', {
    value: () => {},
  });
}

// This is: typeof Bar & { getStatic: () => typeof DataModel; }
const BarWithStatics = addStatics(Bar);
console.log(BarWithStatics.getStatic(), new BarWithStatics().getInstance());

实际上,它正在使用 singleton 实例做一些事情,但是,是的,这就是它的要点。 我希望有一些方法可以做class BarWithStatics = addStatics(Bar)但没有这样的运气。

当然,一旦我提出这个问题,我就会找到解决方案。 您可以扩展 function 的返回:

class BarWithStatics extends addStatics(Bar) {}
interface IFoo {
  bar: BarWithStatics;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM