#if a property is true, the undefined properties will surely exist

5 messages · Page 1 of 1 (latest)

deft jolt
#

I have a type like this

type PaginateResponse<T> = {
    results: Array<T>,
    has_paginate: boolean,
    total_data?: number,
    current_page?: number,
    from?: number,
    to?: number,
    first_page_url?: string,
    last_page?: number,
    last_page_url?: string,
    next_page_url?: string,
    prev_page_url?: string,
    path?: string,
    per_page?: number,
}

I want to make typescript understand that if the has_paginate is true all of the properties that might be undefined will surely exist.
The chat gpt gave a solution:

type PaginateResponse<T> = {
    has_paginate: true;
    total_data: number;
    current_page: number;
    from: number;
    to: number;
    first_page_url: string;
    last_page: number;
    last_page_url: string;
    next_page_url: string;
    prev_page_url: string;
    path: string;
    per_page: number;
} | {
    has_paginate: false;
};

Is this the correct way to achieve this?

tropic geode
deft jolt
#

Not there at all

tropic geode
#

Cool, then that solution should work well

deft jolt
#

Good
I just wanted to make sure that this solution is the best way to achieve that goal