【问题标题】:What is the purpose of the `Exact<T>` type that @graphql-codegen creates?@graphql-codegen 创建的 `Exact<T>` 类型的目的是什么?
【发布时间】:2021-11-14 23:39:57
【问题描述】:

GraphQL Code Generator 在创建的 TypeScript 文件的顶部创建此类型:

export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };

并将其用于所有客户端创建的查询变量:

src/foo.graphql:

query Foo($id: ID!) {
  foo(id: $id) {
    bar
  }
}

generated/foo.ts:

...

export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };

...

export type FooQueryVariables = Exact<{
  id: Scalars['ID'];
}>;

...

这种Exact&lt;T&gt; 类型的用途是什么?它如何影响FooQueryVariables(如果它不存在的话)?


https://www.graphql-code-generator.com/#live-demo的完整演示

schema.graphql:

schema {
  query: Query
}

type Query {
  foo(id: ID!): Foo
}

type Foo {
  bar: String!
}

operation.graphql:

query Foo($id: ID!) {
  foo(id: $id) {
    bar
  }
}

codegen.yml:

generates:
  operations-types.ts:
    plugins:
      - typescript
      - typescript-operations

生成operations-types.ts:

export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
  ID: string;
  String: string;
  Boolean: boolean;
  Int: number;
  Float: number;
};

export type Query = {
  __typename?: 'Query';
  foo?: Maybe<Foo>;
};


export type QueryFooArgs = {
  id: Scalars['ID'];
};

export type Foo = {
  __typename?: 'Foo';
  bar: Scalars['String'];
};

export type FooQueryVariables = Exact<{
  id: Scalars['ID'];
}>;


export type FooQuery = { __typename?: 'Query', foo?: Maybe<{ __typename?: 'Foo', bar: string }> };

【问题讨论】:

  • 它完全“扩展”了类型(在代码编辑器中提供了更好的提示)。考虑type A = { a: number; }; type B = { b: string; }; type C = A &amp; B;...如果您将鼠标悬停在C 上,您将在智能感知中看到A &amp; B。如果将CE 悬停在type CE = Exact&lt;C&gt; 中,您将看到{ a: number; b: string; }。至于为什么会发生这种情况,我会把它留给其他人。见typescriptlang.org/play?#code/…

标签: typescript graphql graphql-codegen


【解决方案1】:

它的目的是使它不能将具有任何附加属性的对象(除了id)作为FooQueryVariables 传递。但它没有这样做:https://github.com/dotansimha/graphql-code-generator/issues/4577

【讨论】:

    猜你喜欢
    • 2020-02-26
    • 2020-12-21
    • 2022-10-17
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2019-04-12
    • 2022-07-31
    相关资源
    最近更新 更多