Closed FINDarkside closed 4 years ago
Example:
interface ValueGenerator {
next(): any;
}
class NumberGenerator implements ValueGenerator {
next(): number {
return 1;
}
}
class StringGenerator implements ValueGenerator {
next(): string {
return 'asd';
}
}
class ArrayGenerator<T extends ValueGenerator> implements ValueGenerator {
private generator: T;
constructor(valueGenerator: T) {
this.generator = valueGenerator;
}
next(): Array<ReturnType<T['next']>> {
return [this.generator.next()];
}
}
const num = new NumberGenerator();
const str = new StringGenerator();
const arr = new ArrayGenerator(str);
// val is string[]
const val = arr.next();
Didn't manage to get this working for my ArrayParser for some reason.
It works if you call new ArrayParser
directly, but not when you call bParse.array
from src/binaryParser/index.ts
.
Example of how it does not work:
abstract class ValueGenerator {
abstract next(): any;
}
class NumberGenerator extends ValueGenerator {
next(): number {
return 1;
}
}
class StringGenerator extends ValueGenerator {
next(): string {
return 'asd';
}
}
class ArrayGenerator<T extends ValueGenerator> extends ValueGenerator {
private generator: T;
constructor(valueGenerator: T) {
super();
this.generator = valueGenerator;
}
next(): Array<ReturnType<T['next']>> {
return [this.generator.next()];
}
}
const num = new NumberGenerator();
const str = new StringGenerator();
const arrCreate = (...param: ConstructorParameters<typeof ArrayGenerator>) => new ArrayGenerator(...param);
const arr = arrCreate(num);
const val = arr.next();
Type inference works for ArrayParser since 8de84bfdd02a34d8f90446e1f93fc605c872bcd7
Would be cool if TS knew that after
obj.a
isNumber
andobj.arr
is array of strings.Not 100% sure if this is possible.