Skip to content

client.query() return type should narrow data to non-null when errorPolicy: "none" #13123

@ItaiYosephi

Description

@ItaiYosephi

Issue Description

Description:

Trying to upgrade to version 4, there's a lot of ts error around promise based api.
When using the promise-based client.query() API with errorPolicy: "none" (the default), the promise rejects on errors and only resolves when data is successfully returned ( see docs). However, the TypeScript return type still shows data as potentially undefined, requiring unnecessary non-null assertions or runtime checks.

const result = await client.query<MyDocumentQuery, MyDocumentVariables>({
  query: MyDocument,
  errorPolicy: 'none', // default
});

// TypeScript error: result.data is possibly undefined
const data: MyDocumentQuery =  result.data; // ❌ Type 'MyDocumentQuery | undefined'

Expected:

the return type of promised-based APIs should have a different return type based on the errorPolicy option.
EDIT: Thinking about it, the default value of errorPolicy can be modified by passing defaultOptions to ApolloClient constructor, so this needs to be taken into consideration

Link to Reproduction

no link

Reproduction Steps

No response

@apollo/client version

4.1.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions