I have a JSON object sent from the server to the browser. From that JSON object I want to check if it is an instance of some class (in other word, check if they class properties exist in the JSON object) without making any loop that will slow my code.
I have the class:
export class MyClass implements IInterface {
type: MyType = "Page";
isAbsolute: boolean = false;
}
IInterface:
export interface IInterface {
type: MyType
}
MyType:
export type MyType = "Page" | "Other"
In just JavaScript I used to check if it's a page like this:
if("type" in theObject && theObject.type === "Page"){
//so it's a page
}
If I have to do it like this in typescript I don't have no reason to do use Typescript over Javascript.
I made some test by creating an object but typeof
and instanceof
cannot know if they are compatible.
let page1 = {'type': "Page", "isAbsolute": true};
let page1Cast = page1 as MyClass;
let anyCast = {"hello": "world"} as MyClass;
let page2 = new MyClass();
page2.isAbsolute = true;
console.log("typeof", typeof page1);
console.log("page1", page1);
console.log("page2", page2);
console.log("page1 instanceof", page1 instanceof MyClass);
console.log("page2 instanceof", page2 instanceof MyClass);
console.log("page1Cast instanceof", page1Cast instanceof MyClass);
console.log("anyCast instanceof", anyCast instanceof MyClass);
The output is:
typeof object
page1 {type: "Page", isAbsolute: true}
page2 MyClass {type: "Page", isAbsolute: true}
page1 instanceof false
page2 instanceof true
page1Cast instanceof false
anyCast instanceof false
How can I check if page1
is typeof MyClass
wihotut doing it like I used to in JS (Check if every property exist and maybe value exists or loop)?