Type guards are used to obtain information about the type of a variable.
Last active
December 27, 2023 16:19
-
-
Save Aberratio/d96211f6812f1387e33cd0e892a26e16 to your computer and use it in GitHub Desktop.
An example of using quards in React.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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