【问题标题】:Typescript - function return type as interfaceTypescript - 函数返回类型作为接口
【发布时间】:2021-07-07 03:59:41
【问题描述】:

我正在研究将函数的返回类型定义为实现接口的类型的可能性

不是实现接口的类型的实例,类型本身

我可以做的类型:

interface A {
  doSomething(): number;
}

class Base implements A {
  doSomething() { return 1; }
}

class Ext1 extends Base {
  doSomething() { return 2; }
}

class Ext2 extends Base {
  doSomething() { return 3; }
}


function process(x: number): typeof Base | null {
  if (x === 1) {
    return Ext1;
  } else if (x === 2) {
    return Ext2;
  }
  return null;
}

根据条件,您的正常工厂功能是什么

问题是,我必须定义我根本不关心的Base 类并做一些A 的虚拟实现

我正在寻找的是:

interface A {
  doSomething(): number;
}


class Ext1 implements A {
  doSomething() { return 2; }
}

class Ext2 implements A {
  doSomething() { return 3; }
}


function process(x: number): typeof A | null {
  if (x === 1) {
    return Ext1;
  } else if (x === 2) {
    return Ext2;
  }
  return null;
}

但发生错误 'A' only refers to a type, but is being used as a value here.ts(2693)

有没有办法做到这一点?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你需要一个构造函数签名:

    function process(x: number): (new () => A) | null { 
        // ...
    }
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2018-09-15
      • 2019-09-27
      相关资源
      最近更新 更多