#Discriminating Unions Without Common Fields

4 messages · Page 1 of 1 (latest)

main dagger
#

Hi. TypeScript recommends to discriminate Union Types with a common field, perhaps "state", that would determine what other fields are available.
This is very nice when this advice is followed. But how should I deal with library / network requests that don't have any discrimination fields? One state has { bunch of data fields }, another has { error, message }. No common fields.
The API treats the response as a Union type, which worked fine when creating the response, but reports zero fields when consuming a response.

#

Example:

API returns a FlashbotsTransaction:

export declare type FlashbotsTransaction = FlashbotsTransactionResponse | RelayResponseError;

FlashbotsTransactionResponse:

export interface FlashbotsTransactionResponse {
    bundleTransactions: Array<TransactionAccountNonce>;
    wait: () => Promise<FlashbotsBundleResolution>;
    simulate: () => Promise<SimulationResponse>;
    receipts: () => Promise<Array<TransactionReceipt>>;
    bundleHash: string;
}

RelayResponseError:

export interface RelayResponseError {
    error: {
        message: string;
        code: number;
    };
}

Union type, as you can see, has zero fields in common, yay.

vital dew
#

you don't need to discriminate them then, just narrow them; "error" in obj should work for making it readable, and you could follow the error-first callback pattern

main dagger
#

Ah, the "key" in obj was the phrase! I tried doing obj.key !== undefined or something like that