Skip to content

Commit

Permalink
add instructions for fragment type-casting (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Apr 28, 2023
1 parent 21722a4 commit 432f6e5
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 1 deletion.
31 changes: 31 additions & 0 deletions packages/example/src/Pokemon.generated.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 18 additions & 1 deletion packages/example/src/Pokemon.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { gql } from '@urql/core';

export const PokemonFields = gql`
fragment pokemonFields on Pokemon {
id
name
attacks {
fast {
damage
name
}
}
}
` as typeof import('./Pokemon.generated').PokemonFieldsFragmentDoc;

export const Pokemon = () => 'hi';
export const Pokemon = (data: any) => {
const pokemon = useFragment(PokemonFields, data);
return `hi ${pokemon.name}`;
};

export function useFragment<Type>(
_fragment: TypedDocumentNode<Type>,
data: any
): Type {
return data;
}
31 changes: 31 additions & 0 deletions packages/graphqlsp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,37 @@ when on a TypeScript file or adding a file like [this](https://github.com/0no-co
- `shouldCheckForColocatedFragments` when turned on (default), this will scan your imports to find
unused fragments and provide a message notifying you about them

## Fragment masking

When we use a `useQuery` that supports `TypedDocumentNode` it will automatically pick up the typings
from the `query` you provide it. However for fragments this could become a bit more troublesome, the
minimal way of providing typings for a fragment would be the following:

```tsx
import { TypedDocumentNode } from '@graphql-typed-document-node/core';

export const PokemonFields = gql`
fragment pokemonFields on Pokemon {
id
name
}
` as typeof import('./Pokemon.generated').PokemonFieldsFragmentDoc;

export const Pokemon = props => {
const pokemon = useFragment(props.pokemon, PokemonFields);
};

export function useFragment<Type>(
_fragment: TypedDocumentNode<Type>,
data: any
): Type {
return data;
}
```

This is mainly needed in cases where this isn't supported out of the box and mainly serves as a way
for you to case your types.

## Local development

Run `pnpm i` at the root. Open `packages/example` by running `code packages/example` or if you want to leverage
Expand Down

0 comments on commit 432f6e5

Please sign in to comment.