Reputation: 237
I am trying to implement a generic discrete interval encoding tree with typescript. Generic here means I want to allow interval endpoints to be arbitrary classes that extends a simple interface specifying discrete linear orders which enforces the existence of two method members next
and lessThan
. Because I want to type the methods I assume I need a generic interface (all the code can be found in this jsfiddle):
interface DiscreteLinearOrder<T> {
next = () => T;
lessThan = (y: T) => Boolean;
}
Then I instantiated this with number (ok, it is not discrete, but think of it as integers ;-)
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()); }
}
Up to here it worked, and running things like
const bar = new DLOnumber(5);
worked out.
Having this I planed to provide a class DLOinterval
that takes two parameters, one extending the discrete linear order interface:
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;
}
}
But here the troubles are starting: I cannot define a type alias and use it:
type NumberInterval = DLOinterval<number, DLOnumber>;
const ggg = new NumberInterval(new DLOnumber(3),new DLOnumber(5),null)
neither can I instantiate it directly:
const aaa = new DLOinterval<number, DLOnumber>(new DLOnumber(3),new DLOnumber(5),null)
What am I missing here?
Upvotes: 0
Views: 669
Reputation: 489
The constraint applied to DLOinterval<T, U extends DiscreteLinearOrder<T>>
doesn't compile due to the mentioned error in the comment section because it will become like a nested infinite constraint. How did it work for you?
The only way it should work correctly is by typing the second constraint as to get past the compiler's objection to typing the template type as T
.
class DLOinterval<V, U extends DiscreteLinearOrder<any>>
To make a working example for a mocha test, I extended the same interface as in the screenshot below:
Upvotes: 0
Reputation: 2371
You do not need to create a type from the DLOinterval
class, you can directly use it as follows:
const ggg = new DLOinterval<number, DLOnumber>( new DLOnumber(3), new DLOnumber(5), null);
Upvotes: 0
Reputation: 852
Try this:
const aaa = new DLOinterval<number, DLOnumber>(new DLOnumber(3), new DLOnumber(5), null);
Upvotes: 1