Skip to content

Instantly share code, notes, and snippets.

@janjakubnanista
Last active May 31, 2020 18:29
Show Gist options
  • Save janjakubnanista/f92792f1bd3d33e9441085281696ca1c to your computer and use it in GitHub Desktop.
Save janjakubnanista/f92792f1bd3d33e9441085281696ca1c to your computer and use it in GitHub Desktop.
TypeScript type guards for an interface
// 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