apollographql / apollographql/apollo-tooling

Bug: an input field which defines a default value results in a required field in the generated typedefs

Open
#1,036 1 comment 2 reactions 0 assignees View on GitHub
🤖 component - codegen
Dominant language
TypeScript
Stars
3k
Forks
460
PR merge metrics
No merged PRs in 30d

Description

```graphql
# schema.graphql
type Mutation {
update(input: UpdateInput!): Boolean
}

input UpdateInput {
foo: String! = ""
}
```

```ts
// test.ts
import gql from 'graphql-tag';

gql`
mutation DoUpdate($input: UpdateInput!) {
update(input: $input)
}
`;
```

```shell
$ apollo client:codegen --target=typescript --localSchemaFile=./schema.graphql --includes='test.ts' --outputFlat types.ts
```

With the above command, these TypeScript types are generated:

```ts
export interface DoUpdate {
update: boolean | null;
}

export interface DoUpdateVariables {
input: UpdateInput;
}

export interface UpdateInput {
foo: string;
}
```

**Intended outcome:**

`foo` in the `UpdateInput` interface should be optional:

```ts
export interface UpdateInput {
foo?: string;
}
```

This is because the GraphQL server will use the defined default value of `""` if nothing is passed in the input object, so the field is not actually required on the client side. See the [GraphQL spec](https://facebook.github.io/graphql/June2018/#sec-Input-Objects):

>If no value is provided for a defined input object field and that field definition provides a default value, the default value should be used. If no default value is provided and the input object field’s type is non‐null, an error should be thrown. Otherwise, if the field is not required, then no entry is added to the coerced unordered map.

**Actual outcome:**

The `foo` field in the `UpdateInput` interface is required:

```ts
export interface UpdateInput {
foo: string;
}
```

**How to reproduce the issue:**

See above.

**Versions**

```shell
$ apollo --version
apollo/2.5.1 darwin-x64 node-v10.15.0
```

Contributor guide

Open the contributing guide

Research direction

Start with the code-generation path exercised by `apollo client:codegen`, using the `schema.graphql` and `test.ts` reproduction. Trace how `UpdateInput.foo` is mapped into the generated TypeScript interface, then verify that a non-null field with a default value becomes optional and that the generated output matches the intended example.

Written by the indexing model from the issue text.

Assessment

Tech stack
graphql, typescript
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.