是否可以在TS中进行类型安全的功能集合?

时间:2019-05-02 18:19:42

标签: typescript interface

我正在编写一个小型库来简化redux的工作,但是我被打字困住了。 我想做的基本上可以归结为以下几点:

  • 父类将动作描述符处理为动作
  • 子类提供了所述描述符

问题是,子进程中定义的类型信息在该过程中丢失了。

最小的测试用例如下:

type callable = (...args: any[]) => any
interface CallableCollection {
    [s: string]: callable
}

class Parent {
    functions: CallableCollection
    constructor() {
        this.functions = this.a;
    }
    get a(): CallableCollection {
        return {};
    }
}

class Child extends Parent {
    get a() {
        return {
            a: (x: string) => x,
            b: (x: number) => x,
        }
    }
}

const test = new Child();
test.a.a(5);//type error
test.functions.a(5);// no type errors

我可以通过使类通用并提供所有需要的类型作为类型参数来使其正常工作,但是从类用户的角度来看,它看起来非常la脚。

是否有一种方法可以使它在TS中正常工作,而无需在泛型类中提供类型作为参数?

1 个答案:

答案 0 :(得分:2)

我想这取决于您的实际用例,但是当有问题的特定类型可以从子类的其他属性派生时,有时您可以使用polymorphic this代替泛型:

interface CallableCollection {
  [s: string]: (...args: any[]) => any;
}

class Parent {
  functions: this["a"]; // polymorphic this and a lookup of "a"
  constructor() {
    this.functions = this.a;
  }
  get a(): CallableCollection {
    return {};
  }
}

class Child extends Parent {
  get a() {
    return {
      a: (x: string) => x,
      b: (x: number) => x
    };
  }
}

const test = new Child();
test.a.a(5); //type error
test.functions.a(5); // type error

这对您有用吗?希望能有所帮助;祝你好运!

相关问题