#Union of two interfaces results in only the common values

1 messages · Page 1 of 1 (latest)

frosty lynx
#

Hey guys I need some backup over here, just wanting to see if I can contribute to a library but not understanding the following behavior, I have the following code:

interface Strapi4ResponseMeta {
    pagination: MetaResponsePaginationByPage | MetaResponsePaginationByOffset;
    [key: string]: unknown;
}
interface MetaResponsePaginationByPage {
    page: number;
    pageSize: number;
    pageCount: number;
    total: number;
}
interface MetaResponsePaginationByOffset {
    start: number;
    limit: number;
    total: number;
}

declare const response: Strapi4ResponseMeta

response.pagination.total

The problem is that when I do response.pagination. I get only autocompletion for total, if I use response.pagination.pageSize I get a TS error saying that it doesn't exist. Why is that? I though that the expression MetaResponsePaginationByPage | MetaResponsePaginationByOffset is saying this shape OR this shape, why I get only the common values? how can I fix this (meaning, I know is one of the shapes from looking at the response, but how can I tell TS is that shape and not the other one)?

barren nimbus
#

I get only autocompletion for total, if I use response.pagination.pageSize I get a TS error saying that it doesn't exist. Why is that?
you cannot access a property that might not exist/be present

#

if you don't know what kind of object you are dealing with, then you can't know its properties, and can't access them

#

you can only access the properties that are available on both possible type

#

to access the unique properties, you need to narrow your object first

#

!hb narrowing

spare hingeBOT
barren nimbus
#

@frosty lynx

frosty lynx
#

Ohhh I see 🤔

#

Makes total sense.. I'm familiar with narrowing but didn't understand this particular behavior