TS: Narrowing a Union Type #10173
-
Hi there, I have a GraphQL query query FETCH($iri: ID!) {
fetch(iri: $iri) {
__typename
... on ScholarlyArticle {
iri
name
abstract
description
author {
... on Person {
iri
name
}
... on Organization {
iri
name
}
}
}
... on Book {
name
description
}
}
} This means that the result of export type FetchQuery = {
__typename?: 'Query',
fetch: { __typename: 'ArchiveComponent', name: string, description?: string | null } | {
__typename: 'ArchiveOrganization',
name: string,
description?: string | null
} | { __typename: 'Book', name: string, description?: string | null } | {
__typename: 'Dataset',
name: string,
description?: string | null,
author: Array<{ __typename?: 'Organization', iri: string, name: string } | {
__typename?: 'Person',
iri: string,
name: string
}>
} | { __typename: 'Organization', name: string, description?: string | null } | {
__typename: 'Person',
name: string,
description?: string | null
} | { __typename: 'ResearchProject', name: string, description?: string | null } | {
__typename: 'ScholarlyArticle',
iri: string,
name: string,
abstract?: string | null,
description?: string | null,
author: Array<{ __typename?: 'Organization', iri: string, name: string } | {
__typename?: 'Person',
iri: string,
name: string
}>
}
}; In TypeScript, the concrete type can be narrowed down: if (data?.fetch.__typename === 'ScholarlyArticle') {
data.fetch.author <-- it is a ScholarlyArticle
} Is there a way to construct a type from {
__typename: 'ScholarlyArticle',
iri: string,
name: string,
abstract?: string | null,
description?: string | null,
author: Array<{ __typename?: 'Organization', iri: string, name: string } | {
__typename?: 'Person',
iri: string,
name: string
}>
} using an approach like mapped types, meaning that there is a mechanism that takes Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
see https://stackoverflow.com/questions/79112838/how-to-create-a-mapped-type-for-a-narrowed-union-type |
Beta Was this translation helpful? Give feedback.
see https://stackoverflow.com/questions/79112838/how-to-create-a-mapped-type-for-a-narrowed-union-type