Skip to content

Commit

Permalink
chore: narrow types of getFromAST.ts with type predicates (#10588)
Browse files Browse the repository at this point in the history
* chore: narrow types of `getFromAST` with type predicates

---------

Co-authored-by: Jerel Miller <[email protected]>
  • Loading branch information
charpeni and jerelmiller authored Feb 22, 2023
1 parent bf25da3 commit 78f6d27
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/utilities/graphql/getFromAST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import {

import { valueToObjectRepresentation } from './storeUtils';

type OperationDefinitionWithName = OperationDefinitionNode & {
name: NonNullable<OperationDefinitionNode['name']>;
};

// Checks the document for errors and throws an exception if there is an error.
export function checkDocument(doc: DocumentNode) {
invariant(
Expand Down Expand Up @@ -43,18 +47,19 @@ export function getOperationDefinition(
): OperationDefinitionNode | undefined {
checkDocument(doc);
return doc.definitions.filter(
definition => definition.kind === 'OperationDefinition',
)[0] as OperationDefinitionNode;
(definition): definition is OperationDefinitionNode =>
definition.kind === 'OperationDefinition',
)[0];
}

export function getOperationName(doc: DocumentNode): string | null {
return (
doc.definitions
.filter(
definition =>
definition.kind === 'OperationDefinition' && definition.name,
(definition): definition is OperationDefinitionWithName =>
definition.kind === 'OperationDefinition' && !!definition.name,
)
.map((x: OperationDefinitionNode) => x!.name!.value)[0] || null
.map((x) => x.name.value)[0] || null
);
}

Expand All @@ -63,12 +68,13 @@ export function getFragmentDefinitions(
doc: DocumentNode,
): FragmentDefinitionNode[] {
return doc.definitions.filter(
definition => definition.kind === 'FragmentDefinition',
) as FragmentDefinitionNode[];
(definition): definition is FragmentDefinitionNode =>
definition.kind === 'FragmentDefinition',
);
}

export function getQueryDefinition(doc: DocumentNode): OperationDefinitionNode {
const queryDef = getOperationDefinition(doc) as OperationDefinitionNode;
const queryDef = getOperationDefinition(doc)!;

invariant(
queryDef && queryDef.operation === 'query',
Expand Down

0 comments on commit 78f6d27

Please sign in to comment.