0

I want to eliminate the any type in the following minimal example. The tables property in the Database class is a map having Table<any> for its value type. However, I want to limit Table<any> to Table<? extends Tuple> but do not know how to do.

class Database {
    private readonly tables = new Map<string, Table<any>>();

    getTable<T extends Tuple>(id: string): Table<T> {
        if (this.tables.has(id)) return this.tables.get(id)!;
        return this.createTable(id);
    }

    private createTable<T extends Tuple>(id: string): Table<T> {
        const created = new FakeTable(id)
        this.tables.set(id, created);
        return created;
    }
}

class FakeTable<T extends Tuple> implements Table<T> {

    constructor(id: string) {}

    queryAll() { return [] }
    insert(tuples: T[]) {}
    delete(tuples: T[]) {}
}

interface Table<T extends Tuple> {
    queryAll(): T[];
    insert(tuples: T[]): void
    delete(tuples: T[]): void
}

type Tuple = Record<string, string | number>;

I have tried:

class Database<D> {
    private readonly tables = new Map<string, Table<D extends Tuple>>();
...

But TypeScript compiler complains that '?' expected.(1005).

private readonly tables = new Map<string, Table<D extends Tuple>>();
                                                     //        ^
                                                     //  '?' expected.(1005)

You can find the minimal example for the code here.

4

0 回答 0