Skip to content

Instantly share code, notes, and snippets.

@javierlopezdeancos
Last active March 12, 2025 16:47
Show Gist options
  • Select an option

  • Save javierlopezdeancos/984ce3b6d9019bb64b996097a0a1e7a6 to your computer and use it in GitHub Desktop.

Select an option

Save javierlopezdeancos/984ce3b6d9019bb64b996097a0a1e7a6 to your computer and use it in GitHub Desktop.
Typeguard in typescript #typescript
interface UserInterface {
id: number;
firstName: string;
lastName: string;
gender: string;
avatar: string;
age: number;
}
interface AdminUserInterface extends UserInterface {
token: string;
addNewUser: () => void;
}
function isAdminUser(user: unknown): user is AdminUserInterface {
if (user !== null && typeof user === "object") {
return "token" in user;
}
return false;
}
// other example
const ACCOUNT = {
USER: "user",
SERVICE: "service",
};
function isAccount(string: unknown): string is Account {
return typeof string === "string" && string in ACCOUNT;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment