If you're simply performing type checking or assertions, you can utilize the instanceof operator. However, if you wish to display the class name, you can access it using data.constructor.name:
class TestClass {}
var instance = new TestClass();
console.log(typeof instance);
// Expected result: "object"
console.log(instance.constructor.name);
// Expected result: "TestClass"
if (instance instanceof TestClass) {
console.log("instance is TestClass");
}
// Expected result: "instance is TestClass"
Explanation behind this approach: typeof operator only works with JavaScript's native data types like string, boolean, object, etc. By examining how TypeScript transpiles into JavaScript, you can understand why JavaScript identifies your instance as an "object" at runtime.
Updated
This method is applicable only for instances created using the new class() constructor. HttpClient does not actually instantiate your class -- it mainly allows you to define the expected response data type for development purposes with TypeScript. HttpClient does not enforce these expectations at runtime. If you need strict type checking during runtime, you may need to create your own type guard function.
For instance, if you have a class similar to:
class TestClass {
prop: string;
constructor() { }
method(): void {}
}
You can construct a type guard like this:
function isTestClass(obj: TestClass | object): obj is TestClass {
// Add necessary type checking logic here
return (<TestClass>obj).method !== undefined &&
(<TestClass>obj).prop !== undefined;
}
To validate your data at runtime:
var obj_a = { prop: "" },
obj_b = { prop: "", method: null };
console.log(isTestClass(obj_a));
// Expected result: false
console.log(isTestClass(obj_b));
// Expected result: true
You can consider making the type guard function a static method of your class.
Additionally, using an interface for response data instead of a class may be beneficial, as it conveys that the received data may not match the expected implementation.
Further details on user-defined type guards at:
https://www.typescriptlang.org/docs/handbook/advanced-types.html