E
E
Evgeny Zhurov2022-01-30 16:48:45
typescript
Evgeny Zhurov, 2022-01-30 16:48:45

How to type such a data object?

I have an object with the following structure:

const someData = {
    isFetched: false,
    pagination: {},
    data: // ???
}


isFetchedis always boolean

paginationalways like this: (and it may or may not be)
type PagePagination = {
  totalDocs: number
  totalPages: number
  page: number
}


But it datasuggests several possible data types. Their number is very limited (7-8), and they are known in advance. However, when creating an interface for the above, const someDatait's silly to specify something like:
interface SomeData = {
    isFetched: boolean,
    pagination?: PagePagination ,
    data: PossibleType1 |  PossibleType2 | PossibleType3 | PossibleType4 | PossibleType5 /// ...etc.
}


Also, it wouldn't solve the type safety problem too much.
What is the best way to proceed in this case? Generic types can only be used in functions (or not?). Is there something like generics, but not for functions, but for variables or object properties?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Karo, 2022-01-30
@Zhuroff

No, generic types can be used in more than just functions

type SomeData<Data = any> = {
    data: Data[];
}
const a: SomeData<number> = {data: [1,2,3]};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question