-3

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)?

user3502626
  • 838
  • 11
  • 34
  • 3
    You have to do it like you used to in JS; TS *doesn't exist at runtime*. – jonrsharpe Jul 14 '19 at 19:24
  • 2
    Possible duplicate of [How to check the object type on runtime in TypeScript?](https://stackoverflow.com/questions/44078205/how-to-check-the-object-type-on-runtime-in-typescript) – JJJ Jul 14 '19 at 19:33
  • 1
    Although "without making any loop that will slow my code" is an impossible requirement because any system that would check the type would have to go through the object. It can't check the object without checking it. Although although, any fear of having any visible performance issue is almost certainly completely unfounded. – JJJ Jul 14 '19 at 19:36

1 Answers1

-1

If you know the type of the JSON object that you're getting from the server, then you can cast it. For example:

interface MyJSONObject {
    someProperty: number
}
fetch(...)
    .then((result) => result.json())
    .then((myObject: MyJSONObject ) => {
        console.log(myObject.someProperty)
    })

Note how no checking of properties is necessary.

But, if you don't know the type of the object, then how could you expect TypeScript to know it? In this case, some kind of property checking is the only way. Type unions make this pretty, however.

interface JSONObjectWithNumber {
    myNumber: number
}
interface JSONObjectWithString {
    myString: string
}
JSONObjectOnServer = JSONObjectWithNumber | JSONObjectWithString
fetch(...)
    .then((result) => result.json())
    .then((myObject: JSONObjectOnServer) => {
        // Conclude type of object, by checking for a conclusive property.
        if ('myNumber' in myObject) {
            // TypeScript automatically concludes, that the object must be JSONObjectWithNumber.
            console.log(myObject.myNumber)
        } else {
            // TypeScript automatically concludes, that the object must be JSONObjectWithString.
            console.log(myObject.myString)
        }
    })
Niilo Keinänen
  • 2,187
  • 1
  • 7
  • 12