f1-2019-results / desktop-client

0 stars 0 forks source link

Full typescript support for binary parser. #4

Closed FINDarkside closed 4 years ago

FINDarkside commented 4 years ago

Would be cool if TS knew that after

const parser = bParse.object({
    a: bParse.uint16(),
    arr: bParse.array(bParse.string().length(5), 5),
});
const obj = parser.parse(buf);

obj.a is Number and obj.arr is array of strings.

Not 100% sure if this is possible.

FINDarkside commented 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.

FINDarkside commented 4 years ago

It works if you call new ArrayParser directly, but not when you call bParse.array from src/binaryParser/index.ts.

FINDarkside commented 4 years ago

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();
FINDarkside commented 4 years ago

Type inference works for ArrayParser since 8de84bfdd02a34d8f90446e1f93fc605c872bcd7