Last active
May 31, 2020 18:29
-
-
Save janjakubnanista/f92792f1bd3d33e9441085281696ca1c to your computer and use it in GitHub Desktop.
TypeScript type guards for an interface
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
// In this made up scenario we are trying to make sure we didn't get | |
// a corrupted piece of data from a WebSocket | |
interface WebSocketMessage { | |
time: number; | |
text: string; | |
description?: string; | |
content: string[]; | |
} | |
// You could also write this as one looong if statement if you prefer | |
const isWebSocketMessage = (value: unknown): value is WebSocketMessage => { | |
if (!value) return false; | |
if (typeof value.time !== 'number') return false; | |
if (typeof value.text !== 'string') return false; | |
if (typeof value.description !== 'string' && value.description !== undefined) return false; | |
if (!Array.isArray(value.content) || !value.content.every(content => typeof content === 'string')) return false; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment