Skip to content

Instantly share code, notes, and snippets.

@kenmori
Last active November 14, 2019 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenmori/a1d6596adaf3fcc8929827f435453009 to your computer and use it in GitHub Desktop.
Save kenmori/a1d6596adaf3fcc8929827f435453009 to your computer and use it in GitHub Desktop.
【GraphQL x TypeScript】Fragmentで返すデータ型をちゃんと絞り込まないとUnion型をoperation時に大変になります

【GraphQL x TypeScript】Fragmentで返すデータ型をちゃんと絞り込まないとUnion型をoperation時に大変になります

graphql-codegen で型定義を生成した後、大変です。 queryを作る際にFragmentを適切にすればその型が手に入るので、 page側で使いたい型を絞り混んで生成して型付けしたいですね。苦労しましたので書く

   const isTxtUnit = (
        unit: GraphqlTypes.TextUnitAndOrganizationPulldownInUnitFragment // Fragmentを最後につければfragment型 
    ): unit is GraphqlTypes.TextUnitOfMemberListFragment => // TextUnitOfMemberList型として絞りこむ
        unit.__typename === 'TextUnit'

    const filteredTextUnits = units.filter(isTxtUnit)

    const mapedTextItemsForUI = filteredTextUnits.map(e => {
        return {
            key: e.id, // 絞り込まれて安全になる
            type: 0,
            label: e.label,
            value: ''
        }
    })
fragment TextUnitAndOrganizationPulldownInUnit on Unit { // UnitUnion... on TextUnit { // 欲しいフィールドを型 > フィールドと絞り込む
        ...TextUnitOfMemberList
    }
    ... on OrganizationPulldownUnit {
        ...OrganizationPulldownUnitOfMemberList // これだけのフィールドを取得する
    }
}
fragment TextUnitOfMemberList on TextUnit {
    id
    label
    value {
        id
        value
    }
    unitType
}
fragment OrganizationPulldownUnitOfMemberList on OrganizationPulldownUnit {
    id
    label
    selections {
        id
        value
        order
    }
    isMultiple
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment