graphql-code-generator-plugin-typescript-typename-typeguards
v0.1.0
Published
A plugin for graphql code generator that generate user defined type guards with __typename
Downloads
5
Maintainers
Readme
GraphQL Code Generator Plugin Typescript Typename Typeguards
This is a plugin for GraphQL Code Generator.
Generate user defined type guard functions from user defined type of schema.
What is a user defined type guard function? https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
Installation
npm install -D graphql-code-generator-plugin-typescript-typename-typeguards
Usage
import type { CodegenConfig } from "@graphql-codegen/cli";
const config: CodegenConfig = {
generates: {
"src/generated/graphql.ts": {
plugins: [
"typescript",
"graphql-code-generator-plugin-typescript-typename-typeguards",
],
},
},
};
export default config;
For GraphQL Code Generator v2
generates:
src/generated/graphql.ts:
plugins:
- typescript
- graphql-code-generator-plugin-typescript-typename-typeguards
Example
Input
type User {
id: ID!
name: String!
age: Int!
email: String!
address: Address!
friends: [User!]!
}
type Address {
country: String!
prefecture: String!
city: String!
street: String!
}
Output
export const isUser = (field: { __typename?: string }): field is User =>
field.__typename === "User";
export const isAddress = (field: { __typename?: string }): field is Address =>
field.__typename === "Address";
Config
argsAsStringLiteralUnion
If true, the type guard function's args will be generated as a string literal union.
const config: CodegenConfig = {
generates: {
"src/generated/graphql.ts": {
plugins: [
"typescript",
"graphql-code-generator-plugin-typescript-typename-typeguards",
],
config: {
argsAsStringLiteralUnion: true,
},
},
},
};
export const isUser = (field: {
__typename?: "User" | "Address";
}): field is User => field.__typename === "User";
export const isAddress = (field: {
__typename?: "User" | "Address";
}): field is Address => field.__typename === "Address";
License(MIT)
See LICENSE