What is the best way to check a variable's type in TypeScript?

What is the best way to check a variable’s type in TypeScript?

In ActionScript, you can check a variable’s type at runtime using the is operator:

var mySprite:Sprite = new Sprite(); 
trace(mySprite is Sprite); // true 
trace(mySprite is DisplayObject); // true 
trace(mySprite is IEventDispatcher); // true

Is there a way to perform a similar check type TypeScript operation to determine if a variable is an instance of a specific class or implements an interface?

I couldn’t find clear details in the TypeScript language specs, but class and interface type-checking seem essential in certain scenarios. What are the best practices for achieving this?

The instanceof operator is the most straightforward way to check if an object is an instance of a specific class or constructor function. This method works for classes, but it won’t work for interfaces since TypeScript interfaces do not exist at runtime (they are only used at compile-time for type checking).

class MyClass {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

const myInstance = new MyClass('Hello');

console.log(myInstance instanceof MyClass);  // true

Note: instanceof checks if the variable is an instance of a class, not if it implements an interface.

agree to @shilpa.chandel but you can typeof For primitive types (like string, number, etc.) to check the type. It doesn’t work for classes or interfaces but is useful for basic types.

let myString = 'Hello';
let myNumber = 10;

console.log(typeof myString === 'string'); // true
console.log(typeof myNumber === 'number'); // true

The unary plus (+) is the most concise and efficient way to convert a string to a number in TypeScript. It attempts to convert the string to a number directly and returns NaN if the conversion fails. This is a quick and effective method, especially for simple cases.

let numberString: string = "1234";
let numberValue: number = +numberString;

console.log(numberValue);  // 1234

This method directly converts the string to a number, and if the string contains any non-numeric characters, it returns NaN.