【问题标题】:TypeScript Generic sub typeTypeScript 通用子类型
【发布时间】:2017-06-24 17:42:37
【问题描述】:

是否可以将命名空间作为通用类型传递,然后从命名空间访问类型?我想实现这样的目标:

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>;

【问题讨论】:

  • 不,你不能那样做。但也许你可以详细说明你为什么要开始这样做?你的真实情况是什么?
  • 我正在使用 Angular2 和 Apollo 构建一个应用程序。我正在使用gql-gen 来生成类型。它为每个查询生成一个命名空间,并在其中添加 ResultVariables 类型。我想在我的泛型类型中使用那些同时使用ResultVariables 并希望使用Cast&lt;UpvotePostMutation&gt; 而不是Cast&lt;UpvotePostMutation.Result, UpvotePostMutation.Variables&gt;。太糟糕了,这是不可能的,但感谢澄清:)。

标签: typescript typescript-generics


【解决方案1】:

我不确定我是否理解你,但如果我理解了,那么如何:

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)


编辑

你可以用你想要的query函数做类似的事情:

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)

【讨论】:

  • 不完全是我需要的。我想像query(data: {query: any, variables?: Variables}): ApolloQueryObservable&lt;Result&gt;; 一样使用它,所以VariablesResult 是分开的。
  • 是的,但这仍然通过了 R 和 V 泛型:P。我希望只通过他们的容器并在里面“解包”;)。
  • 您没有“传递”任何泛型,编译器会根据“容器”命名空间自行推断。
猜你喜欢
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 2019-08-21
  • 2015-12-10
  • 2016-01-16
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
相关资源
最近更新 更多