首页 > 解决方案 > Typescript:从函数的返回中定义类类型(并将其用作类型)

问题描述

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

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.
}

真实世界的用例是我有一个函数,它使用类的泛型类型向类添加一些静态方法。所以,

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());

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

标签: typescripttypescript-typingstypescript-genericsstatic-typingtypescript-class

解决方案


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

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

推荐阅读