Dracco
Dracco

Reputation: 443

TypeScript Generic sub type

Is that possible to pass a namespace as a generic and later access types from the namespace? I would like to achieve something like that:

namespace Test {
  export type A = { ... }
  export type B = { ... }
}

type Gen<T> = (a: T.A, b: T.B) => void;

// using Gen<T>
let x: Gen<Test>;

Upvotes: 1

Views: 630

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164357

I'm not exactly sure that I understand you, but if I do, then how about this:

namespace Test {
    export const Result = {
        num: 3
    }

    export const Variables = {
        str: "string"
    }
}

interface MyNamespace<R, V> {
    Result: R;
    Variables: V;
}

function Gen<R, V>(namespace: MyNamespace<R, V>): void {}

Gen(Test);

(code in playground)


Edit

You can do something similar with the query function you want:

function query<R, V>(namespace: MyNamespace<R, V>, data: { query: any, variables?: V }): Array<R> {
    return [];    
}

// type of arr is { num: number; }[]
let arr = query(Test, { query: "query", variables: { str: "" } });

(code in playground)

Upvotes: 1

Related Questions