2

请看这段代码:

interface A<T> {
    method1(): A<T>;
}

interface B<T extends Function> extends A<T> {
    method2(): B<T>;
}

var foo: A<Function>;
foo.method1();
foo.method2();

我希望foo与该B<Function>类型兼容,但我得到了error TS2339: Property 'method2' does not exist on type 'A<Function>'. 我可以B以某种方式重写接口以使其工作吗?

实际上,我正在尝试修复 lodash 的类型_.memoize

// This should be OK. The type of result1 should be compatible with aFunction.
var result1 = _(aFunction).memoize().value();

// And this should be an error.
var result2 = _(aNonFunctionValue).memoize().value();

更新。基本上,我的问题是:我是否可以编写这样一个通用方法,A<T>只有当T它是其他类型的子类型时它才可用U

4

2 回答 2

3

我可以以某种方式重写接口 B 以使其工作吗?

解决方案

这是代码:

interface A<T> {
    method1(): A<T>;
}

interface B<T extends Function> extends A<T> {
    method2(): B<T>;
}

interface A<T> {
    method2<T extends Function>(): B<T>;
}

var foo: A<Function>;
foo.method1();
foo.method2(); // works!

到达解决方案

让我们退后一步,想想我们想要做什么:

var foo: A<Function>;
foo.method2(); // Should work

这意味着A<Function>应该有method2它。所以:

interface A<T> {
    method2<T extends Function>(): B<T>;
}

并且这个方法二添加了一个泛型约束T并返回一些类型B

其余的在最终解决方案中很清楚

于 2016-01-17T23:49:29.080 回答
1

结果 TypeScript 不支持这个。请参阅https://github.com/Microsoft/TypeScript/issues/1290

2019 年更新:现在我们有了Conditional Types,这是小菜一碟:

interface A<T> {
    method1(): A<T>;
    method2: T extends Function ? () => A<T> : never;
}

declare var foo: A<Function>;
foo.method1();
foo.method2();
于 2016-01-18T22:39:22.310 回答