Skip to content

Instantly share code, notes, and snippets.

@Jinksi
Last active September 25, 2023 01:24
Show Gist options
  • Save Jinksi/24b98fb876a6e2bf4e63d5aad58841d3 to your computer and use it in GitHub Desktop.
Save Jinksi/24b98fb876a6e2bf4e63d5aad58841d3 to your computer and use it in GitHub Desktop.
An example of using TypeScript type guard functions
interface LostDispute {
status: 'lost';
metadata: {
// Mandatory for lost disputes
__dispute_closed_at: string;
// Optional for lost disputes
__evidence_submitted_at?: string;
}
}
interface UnderReviewDispute {
status: 'under_review';
metadata: {
// Mandatory for under_review disputes
__evidence_submitted_at: string;
}
}
type Dispute = LostDispute | UnderReviewDispute;
const isLostDispute = (dispute: Dispute): dispute is LostDispute => {
// You could also check for the required metadata here, but it is probably better to ensure the TS interfaces are accurate and trustworthy
return dispute.status === 'lost';
}
const isUnderReviewDispute = (dispute: Dispute): dispute is UnderReviewDispute => {
return dispute.status === 'under_review';
}
// Using the
const DisputeMetadataExample: React.FC< {
dispute: Dispute;
} > = ( { dispute } ) => {
if ( isUnderReviewDispute( dispute ) ) {
return (
// We can guarantee that the `__evidence_submitted_at` metadata will be present here because we used the isUnderReviewDispute type guard function
<div>Submitted: { dispute.metadata.__evidence_submitted_at }</div>
);
}
if ( isLostDispute( dispute ) ) {
// We can guarantee that the `__dispute_closed_at` metadata will be present here because we used the isLostDispute type guard function
return <div>Closed: { dispute.metadata.__dispute_closed_at }</div>;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment