Câu hỏi phỏng vấn Typescript
Câu hỏi

How to check the type of a variable or constant in TypeScript?

Câu trả lời

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:

Using the typeof Operator

The 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.

typescript Copy
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].

Using the instanceof Operator

For 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.

typescript Copy
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].

Custom Type Guards

TypeScript allows for the creation of custom type guards to check the type of variables or objects. This is particularly useful whe...

middle

middle

Gợi ý câu hỏi phỏng vấn

entry

How to call base class constructor from child class in TypeScript?

expert

What does the tsconfig option lib do?

junior

Does TypeScript support all object oriented principles?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào