Connectome-Implementation-Team / react-graphql

React app based on GraphQL schema
MIT License
0 stars 0 forks source link

Narrow Type From Union #7

Open tobiasschweizer opened 2 hours ago

tobiasschweizer commented 2 hours ago

TypeScript types for the GraphQL schema are generated by https://github.com/dotansimha/graphql-code-generator

Union types are expressed as TS unions.

Here is how to create more specific types for a union:

type ResultUnion = FetchQuery['fetch']

type Specific<T extends ResultUnion, N extends 'ScholarlyArticle' | 'Book' | 'Dataset' | 'ResearchProject' | 'Organization' | 'Person' | 'ArchiveComponent' | 'ArchiveOrganization'> = {

    [P in keyof T]:
        T['__typename'] extends N ? T : never

}[keyof T]

export type ScholarlyArticle = Specific<ResultUnion, 'ScholarlyArticle'>

export type Book = Specific<ResultUnion, 'Book'>

see also https://stackoverflow.com/questions/79112838/typescript-create-new-type-for-narrowed-union-type#79112838

tobiasschweizer commented 2 hours ago