How to determine variable type in TypeScript: typeof, instanceof and custom checks
Hello everyone! I just started learning TypeScript and ran into a problem: how to find out what type a variable has during program execution? In regular JavaScript I used `typeof`, but in TS it doesn't always work as I expect.\n\nHere's an example code that confuses me:\n\n```typescript\nlet value: string | number = "hello";\n\n// Trying to check the type\nif (typeof value === "string") {\n console.log(value.toUpperCase()); // Works\n}\n\nvalue = 42;\nif (typeof value === "number") {\n console.log(value.toFixed(2)); // Works\n}\n\n// But with objects it's more complicated\ninterface User {\n name: string;\n age: number;\n}\n\ninterface Admin {\n name: string;\n role: string;\n}\n\nfunction processUser(user: User | Admin) {\n // How to check here whether it's User or Admin
No answers yet.
Log in to leave an answer