1

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>;
2
  • 2
    No, you can't do that. But maybe you can elaborate on why you would like to do that to begin with? What's your real scenario? Commented Feb 7, 2017 at 13:13
  • I am building an app using Angular2 and Apollo. I am using a gql-gen to generate types. It generates a namespaces per query, and inside it adds Result and Variables types. I would like to use those in my generic type which uses both Result and Variables and was hoping to do Cast<UpvotePostMutation> instead of Cast<UpvotePostMutation.Result, UpvotePostMutation.Variables>. Too bad it's not possible, but thanks for clarifying :). Commented Feb 7, 2017 at 13:19

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Not exactly what I needed. I wanted to use it like query(data: {query: any, variables?: Variables}): ApolloQueryObservable<Result>; so Variables and Result are separate.
Yea, but this is still passing both R and V generics :P. I was hoping to pass just their container and "unpack" them inside ;).
You are not "passing" any generics, the compiler infers that on its' own based on the "container" namespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.