Middle
What are typeof and instanceof in TypeScript, and how are they used?
sobes.tech AI
Answer from AI
typeof and instanceof are operators used in TypeScript (and JavaScript) to check types, but they work differently.
typeofreturns a string describing the primitive type of a value (e.g., "string", "number", "boolean", "undefined", "object", "function"). It is used for checking primitive types.
const value = "hello";
if (typeof value === "string") {
// value is a string
}
instanceofchecks whether an object is an instance of a specific class or constructor. It works with objects and classes.
class User {}
const user = new User();
if (user instanceof User) {
// user is an instance of User
}
In TypeScript, these operators are often used for type narrowing in conditional statements, so the compiler understands the specific type of a variable and allows safe access to its properties.