In TypeScript, determining the type of a variable can be done in various ways. Here are some commonly used methods:
1. Using the typeof Operator
The typeof operator can be used to obtain the basic type of a variable, such as string, number, boolean, etc. This is also supported in JavaScript, but in TypeScript, it can be used in type guards and type inference.
Example:
typescriptlet age: number = 30; let ageType: string = typeof age; // 'number' if (typeof age === 'number') { console.log('Age is a number.'); }
2. Using the instanceof Operator
When you need to verify if an object is an instance of a specific class, you can use the instanceof operator. This is very useful when dealing with classes and inheritance.
Example:
typescriptclass Person { name: string; constructor(name: string) { this.name = name; } } let person = new Person("Alice"); if (person instanceof Person) { console.log('person is an instance of Person'); }
3. Custom Type Guard Functions
TypeScript allows defining your own type guard logic by creating a function that returns a type predicate.
Example:
typescriptfunction isNumber(x: any): x is number { return typeof x === "number"; } function process(input: number | string) { if (isNumber(input)) { console.log('Input is a number'); } else { console.log('Input is a string'); } } process(10); // Output: Input is a number process("Hello"); // Output: Input is a string
4. Using TypeScript Type Queries
TypeScript provides a syntax for obtaining the type of a variable using the typeof keyword in a type context.
Example:
typescriptlet initial = "test"; let StringType = typeof initial; // 'string' let num: StringType; num = "Hello"; // Correct num = 123; // Error: Type 'number' is not assignable to type 'string'
These methods can be chosen based on your specific requirements and context. In actual development, correctly identifying and using types not only helps us better leverage TypeScript's strong typing system but also improves code maintainability and readability.