【发布时间】:2018-09-15 23:25:09
【问题描述】:
我正在尝试用 typescript 实现一个通用的discrete interval encoding tree。这里的泛型意味着我希望允许区间端点是任意类,这些类扩展了一个指定离散线性顺序的简单接口,该接口强制存在两个 method 成员 next 和 lessThan。因为我想键入我假设我需要一个通用接口的方法(所有代码都可以在这个jsfiddle中找到):
interface DiscreteLinearOrder<T> {
next = () => T;
lessThan = (y: T) => Boolean;
}
然后我用数字实例化它(好吧,它不是离散的,但可以将它视为整数;-)
class DLOnumber implements DiscreteLinearOrder<number> {
private value: number;
constructor(x: number) { this.value = x; }
next = () => { return(this.value + 1); };
lessThan = (y: number) => { return(this.value < y); };
getValue = () => { return(this.value.toString()); }
}
到这里为止它工作正常,并且运行类似
const bar = new DLOnumber(5);
解决了。
有了这个,我打算提供一个类DLOinterval,它接受两个参数,一个扩展离散线性顺序接口:
class DLOinterval<T, U extends DiscreteLinearOrder<T>> {
private start: U;
private end: U;
private data: any;
constructor(s: U, e: U, d: any) {
this.start = s;
this.end = e;
this.data = d;
}
}
但是麻烦开始了:我无法定义类型别名并使用它:
type NumberInterval = DLOinterval<number, DLOnumber>;
const ggg = new NumberInterval(new DLOnumber(3),new DLOnumber(5),null)
我也不能直接实例化它:
const aaa = new DLOinterval<number, DLOnumber>(new DLOnumber(3),new DLOnumber(5),null)
我在这里错过了什么?
【问题讨论】:
-
当您将 NumberInterval 定义为
type NumberInterval = DLOInterval<number, DLOnumber>;时,您定义的是一个类型,而不是类构造函数,所以我认为您不应该调用new NumberInterval(...)。另外请注意,在type NumberInterval = DLOInterval<number, DLOnumber>;中,DLOinterval 应使用小写的“i”(基于您的类构造函数)。 -
谢谢,已解决。
-
此未决问题可能与此处相关:github.com/Microsoft/TypeScript/issues/1213
-
啊啊,太好了!!!这就是我正在寻找的。span>
标签: typescript generics interface