TS: Narrowing a Union Type #10173
Unanswered
tobiasschweizer
asked this question in
Q&A
Replies: 1 comment
-
Ok, here is something: type ResultUnion = { __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
}>
}
type Specific<T extends ResultUnion, N extends 'Book' | 'ScholarlyArticle' | 'Organization' | 'Dataset'> = {
[P in keyof T]:
T[P] extends N ? T : never
}[keyof T]
type ScholarlyArticle = Specific<ResultUnion, 'ScholarlyArticle'>
type Book = Specific<ResultUnion, 'Book'>
const myBook: Book = {
__typename: 'Book',
name: 'myBook',
description: 'Interesting Book'
}
type Dataset = Specific<ResultUnion, 'Dataset'>
const myDataset: Dataset = {
__typename: 'Dataset',
name: 'A dataset',
author: [
{
__typename: 'Person',
iri: 'an ID',
name: 'author'
}
],
description: 'A description'
} I'll still have to think a bit about this, but it seems a starting point ... |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi there,
I have a GraphQL query
fetch
that returns a union typeResultUnion
which groups types such asBook
,ScholarlyArticle
etc.This means that the result of
fetch
is either aBook
or aScholarlyArticle
etc.In TypeScript, the concrete type can be narrowed down:
Is there a way to construct a type from
FetchQuery
that is justusing an approach like mapped types, meaning that there is a mechanism that takes
FetchQuery
and produces a type forScholarlyArticle
given the informationfetch.__typename === 'ScholarlyArticle'
?Thanks!
Beta Was this translation helpful? Give feedback.
All reactions