aronfischer
aronfischer

Reputation: 23

Property doesn't exist on type "object" error after checking if the property exists on the object

Issue: I am trying to create a type guard, which should check if some values exist on a property of type unknown.

interface TestProps {
    count: number;
}

const getIsTestShown = (test: unknown): test is TestProps => {
    if (test && typeof test === "object") {
        if ("count" in test) {
            if (typeof test.count === "number") {  // ERROR: Property 'count' does not exist on type 'object'.ts(2339)

                return true;
            }
        }
    }

    return false;
};

The above example is simplified, but represents exactly my problem. Typescript doesn't seem to understand that if "count" in test is true, count should be accessible on test. What am I missing?

Upvotes: 2

Views: 785

Answers (1)

user13258211
user13258211

Reputation:

You could try this:

interface TestProps {
    count: number;
}

const getIsTestShown = (test: any): test is TestProps => {
    return typeof test?.count === "number" ?? false;
};

console.log(getIsTestShown({})) // false
console.log(getIsTestShown({ count: 1 })) // true
console.log(getIsTestShown({ count: "1" })); // false
console.log(getIsTestShown({ someOtherProp: "1" })); // false

If linters tell you not to use any, I would suggest to disable them for this particular function, since you're already checking the existence of the property and the type.

Edit: Here is a more detailed example of how you could use unknown and why it doesn't work just like any.

Upvotes: 1

Related Questions