How to check the type of a variable or constant in TypeScript?
How to check the type of a variable or constant in TypeScript?
In TypeScript, checking the type of a variable or constant can be achieved using several methods, primarily through the typeof
operator, but also with other techniques like the instanceof
operator and custom type guards for more complex scenarios. Here's a detailed explanation:
typeof
OperatorThe typeof
operator is a standard JavaScript operator that TypeScript recognizes for checking the type of variables and constants. It returns a string indicating the type of the operand. This operator is particularly useful for primitive values such as strings, numbers, and booleans. For example, to check the type of a variable x
, you would use typeof x
.
let x: any = "Hello, TypeScript!";
console.log(typeof x); // Output: string
This method is straightforward and works similarly in both JavaScript and TypeScript[1][2].
instanceof
OperatorFor objects, classes, and arrays, where typeof
might not provide the expected results, the instanceof
operator can be more appropriate. This operator checks if an object is an instance of a specific class or constructor function.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
let person = new Person("John");
console.log(person instanceof Person); // Output: true
This approach is useful for more complex data structures beyond primitive types[1].
TypeScript allows for the creation of custom type guards to check the type of variables or objects. This is particularly useful whe...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào