Skip to content

Instantly share code, notes, and snippets.

@Aberratio
Last active December 27, 2023 16:19
Show Gist options
  • Save Aberratio/d96211f6812f1387e33cd0e892a26e16 to your computer and use it in GitHub Desktop.
Save Aberratio/d96211f6812f1387e33cd0e892a26e16 to your computer and use it in GitHub Desktop.
An example of using quards in React.

Type guards are used to obtain information about the type of a variable.

import React from "react";
import { BlogItem, isLongPostBody } from "./types";
const BlogItemPreview = (blogItem: BlogItem) => {
const { body, author, title } = blogItem;
const image = isLongPostBody(body) && body.image;
const previewText = isLongPostBody(body) ? body.lead : body.summary;
return (
<div>
<h2>{title}</h2>
<i>{author}</i>
{image && <image src={image} />}
<p>{previewText}</p>
</div>
);
};
export default BlogItemPreview;
export interface LongPost {
lead: string;
content: string;
image: string;
}
export interface ShortPost {
summary: string;
}
export type BlogBody = ShortPost | LongPost;
export interface BlogItem {
title: string;
author: string;
body: BlogBody;
}
export const isShortPostBody = (body: BlogBody): body is ShortPost =>
'summary' in body;
export const isLongPostBody = (body: BlogBody): body is LongPost =>
'lead' in body;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment